sheet.go 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.15 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/json"
  15. "encoding/xml"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "reflect"
  25. "regexp"
  26. "strconv"
  27. "strings"
  28. "unicode/utf8"
  29. "github.com/mohae/deepcopy"
  30. )
  31. // NewSheet provides the function to create a new sheet by given a worksheet
  32. // name and returns the index of the sheets in the workbook
  33. // (spreadsheet) after it appended. Note that when creating a new spreadsheet
  34. // file, the default worksheet named `Sheet1` will be created.
  35. func (f *File) NewSheet(name string) int {
  36. // Check if the worksheet already exists
  37. index := f.GetSheetIndex(name)
  38. if index != -1 {
  39. return index
  40. }
  41. f.DeleteSheet(name)
  42. f.SheetCount++
  43. wb := f.workbookReader()
  44. sheetID := 0
  45. for _, v := range wb.Sheets.Sheet {
  46. if v.SheetID > sheetID {
  47. sheetID = v.SheetID
  48. }
  49. }
  50. sheetID++
  51. // Update docProps/app.xml
  52. f.setAppXML()
  53. // Update [Content_Types].xml
  54. f.setContentTypes("/xl/worksheets/sheet"+strconv.Itoa(sheetID)+".xml", ContentTypeSpreadSheetMLWorksheet)
  55. // Create new sheet /xl/worksheets/sheet%d.xml
  56. f.setSheet(sheetID, name)
  57. // Update workbook.xml.rels
  58. rID := f.addRels(f.getWorkbookRelsPath(), SourceRelationshipWorkSheet, fmt.Sprintf("/xl/worksheets/sheet%d.xml", sheetID), "")
  59. // Update workbook.xml
  60. f.setWorkbook(name, sheetID, rID)
  61. return f.GetSheetIndex(name)
  62. }
  63. // contentTypesReader provides a function to get the pointer to the
  64. // [Content_Types].xml structure after deserialization.
  65. func (f *File) contentTypesReader() *xlsxTypes {
  66. var err error
  67. if f.ContentTypes == nil {
  68. f.ContentTypes = new(xlsxTypes)
  69. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML("[Content_Types].xml")))).
  70. Decode(f.ContentTypes); err != nil && err != io.EOF {
  71. log.Printf("xml decode error: %s", err)
  72. }
  73. }
  74. return f.ContentTypes
  75. }
  76. // contentTypesWriter provides a function to save [Content_Types].xml after
  77. // serialize structure.
  78. func (f *File) contentTypesWriter() {
  79. if f.ContentTypes != nil {
  80. output, _ := xml.Marshal(f.ContentTypes)
  81. f.saveFileList("[Content_Types].xml", output)
  82. }
  83. }
  84. // getWorkbookPath provides a function to get the path of the workbook.xml in
  85. // the spreadsheet.
  86. func (f *File) getWorkbookPath() (path string) {
  87. if rels := f.relsReader("_rels/.rels"); rels != nil {
  88. for _, rel := range rels.Relationships {
  89. if rel.Type == SourceRelationshipOfficeDocument {
  90. path = strings.TrimPrefix(rel.Target, "/")
  91. return
  92. }
  93. }
  94. }
  95. return
  96. }
  97. // getWorkbookRelsPath provides a function to get the path of the workbook.xml.rels
  98. // in the spreadsheet.
  99. func (f *File) getWorkbookRelsPath() (path string) {
  100. wbPath := f.getWorkbookPath()
  101. wbDir := filepath.Dir(wbPath)
  102. if wbDir == "." {
  103. path = "_rels/" + filepath.Base(wbPath) + ".rels"
  104. return
  105. }
  106. path = strings.TrimPrefix(filepath.Dir(wbPath)+"/_rels/"+filepath.Base(wbPath)+".rels", "/")
  107. return
  108. }
  109. // workbookReader provides a function to get the pointer to the workbook.xml
  110. // structure after deserialization.
  111. func (f *File) workbookReader() *xlsxWorkbook {
  112. var err error
  113. if f.WorkBook == nil {
  114. wbPath := f.getWorkbookPath()
  115. f.WorkBook = new(xlsxWorkbook)
  116. if _, ok := f.xmlAttr[wbPath]; !ok {
  117. d := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(wbPath))))
  118. f.xmlAttr[wbPath] = append(f.xmlAttr[wbPath], getRootElement(d)...)
  119. f.addNameSpaces(wbPath, SourceRelationship)
  120. }
  121. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(wbPath)))).
  122. Decode(f.WorkBook); err != nil && err != io.EOF {
  123. log.Printf("xml decode error: %s", err)
  124. }
  125. }
  126. return f.WorkBook
  127. }
  128. // workBookWriter provides a function to save workbook.xml after serialize
  129. // structure.
  130. func (f *File) workBookWriter() {
  131. if f.WorkBook != nil {
  132. output, _ := xml.Marshal(f.WorkBook)
  133. f.saveFileList(f.getWorkbookPath(), replaceRelationshipsBytes(f.replaceNameSpaceBytes(f.getWorkbookPath(), output)))
  134. }
  135. }
  136. // workSheetWriter provides a function to save xl/worksheets/sheet%d.xml after
  137. // serialize structure.
  138. func (f *File) workSheetWriter() {
  139. var arr []byte
  140. buffer := bytes.NewBuffer(arr)
  141. encoder := xml.NewEncoder(buffer)
  142. for p, sheet := range f.Sheet {
  143. if sheet != nil {
  144. for k, v := range sheet.SheetData.Row {
  145. f.Sheet[p].SheetData.Row[k].C = trimCell(v.C)
  146. }
  147. if sheet.SheetPr != nil || sheet.Drawing != nil || sheet.Hyperlinks != nil || sheet.Picture != nil || sheet.TableParts != nil {
  148. f.addNameSpaces(p, SourceRelationship)
  149. }
  150. // reusing buffer
  151. _ = encoder.Encode(sheet)
  152. f.saveFileList(p, replaceRelationshipsBytes(f.replaceNameSpaceBytes(p, buffer.Bytes())))
  153. ok := f.checked[p]
  154. if ok {
  155. delete(f.Sheet, p)
  156. f.checked[p] = false
  157. }
  158. buffer.Reset()
  159. }
  160. }
  161. }
  162. // trimCell provides a function to trim blank cells which created by fillColumns.
  163. func trimCell(column []xlsxC) []xlsxC {
  164. rowFull := true
  165. for i := range column {
  166. rowFull = column[i].hasValue() && rowFull
  167. }
  168. if rowFull {
  169. return column
  170. }
  171. col := make([]xlsxC, len(column))
  172. i := 0
  173. for _, c := range column {
  174. if c.hasValue() {
  175. col[i] = c
  176. i++
  177. }
  178. }
  179. return col[0:i]
  180. }
  181. // setContentTypes provides a function to read and update property of contents
  182. // type of the spreadsheet.
  183. func (f *File) setContentTypes(partName, contentType string) {
  184. content := f.contentTypesReader()
  185. content.Overrides = append(content.Overrides, xlsxOverride{
  186. PartName: partName,
  187. ContentType: contentType,
  188. })
  189. }
  190. // setSheet provides a function to update sheet property by given index.
  191. func (f *File) setSheet(index int, name string) {
  192. ws := xlsxWorksheet{
  193. Dimension: &xlsxDimension{Ref: "A1"},
  194. SheetViews: &xlsxSheetViews{
  195. SheetView: []xlsxSheetView{{WorkbookViewID: 0}},
  196. },
  197. }
  198. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  199. f.sheetMap[trimSheetName(name)] = path
  200. f.Sheet[path] = &ws
  201. f.xmlAttr[path] = append(f.xmlAttr[path], NameSpaceSpreadSheet)
  202. }
  203. // setWorkbook update workbook property of the spreadsheet. Maximum 31
  204. // characters are allowed in sheet title.
  205. func (f *File) setWorkbook(name string, sheetID, rid int) {
  206. content := f.workbookReader()
  207. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  208. Name: trimSheetName(name),
  209. SheetID: sheetID,
  210. ID: "rId" + strconv.Itoa(rid),
  211. })
  212. }
  213. // relsWriter provides a function to save relationships after
  214. // serialize structure.
  215. func (f *File) relsWriter() {
  216. for path, rel := range f.Relationships {
  217. if rel != nil {
  218. output, _ := xml.Marshal(rel)
  219. if strings.HasPrefix(path, "xl/worksheets/sheet/rels/sheet") {
  220. output = f.replaceNameSpaceBytes(path, output)
  221. }
  222. f.saveFileList(path, replaceRelationshipsBytes(output))
  223. }
  224. }
  225. }
  226. // setAppXML update docProps/app.xml file of XML.
  227. func (f *File) setAppXML() {
  228. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  229. }
  230. // replaceRelationshipsBytes; Some tools that read spreadsheet files have very
  231. // strict requirements about the structure of the input XML. This function is
  232. // a horrible hack to fix that after the XML marshalling is completed.
  233. func replaceRelationshipsBytes(content []byte) []byte {
  234. oldXmlns := []byte(`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships`)
  235. newXmlns := []byte("r")
  236. return bytesReplace(content, oldXmlns, newXmlns, -1)
  237. }
  238. // SetActiveSheet provides a function to set the default active sheet of the
  239. // workbook by a given index. Note that the active index is different from the
  240. // ID returned by function GetSheetMap(). It should be greater or equal to 0
  241. // and less than the total worksheet numbers.
  242. func (f *File) SetActiveSheet(index int) {
  243. if index < 0 {
  244. index = 0
  245. }
  246. wb := f.workbookReader()
  247. for activeTab := range wb.Sheets.Sheet {
  248. if activeTab == index {
  249. if wb.BookViews == nil {
  250. wb.BookViews = &xlsxBookViews{}
  251. }
  252. if len(wb.BookViews.WorkBookView) > 0 {
  253. wb.BookViews.WorkBookView[0].ActiveTab = activeTab
  254. } else {
  255. wb.BookViews.WorkBookView = append(wb.BookViews.WorkBookView, xlsxWorkBookView{
  256. ActiveTab: activeTab,
  257. })
  258. }
  259. }
  260. }
  261. for idx, name := range f.GetSheetList() {
  262. ws, err := f.workSheetReader(name)
  263. if err != nil {
  264. // Chartsheet or dialogsheet
  265. return
  266. }
  267. if ws.SheetViews == nil {
  268. ws.SheetViews = &xlsxSheetViews{
  269. SheetView: []xlsxSheetView{{WorkbookViewID: 0}},
  270. }
  271. }
  272. if len(ws.SheetViews.SheetView) > 0 {
  273. ws.SheetViews.SheetView[0].TabSelected = false
  274. }
  275. if index == idx {
  276. if len(ws.SheetViews.SheetView) > 0 {
  277. ws.SheetViews.SheetView[0].TabSelected = true
  278. } else {
  279. ws.SheetViews.SheetView = append(ws.SheetViews.SheetView, xlsxSheetView{
  280. TabSelected: true,
  281. })
  282. }
  283. }
  284. }
  285. }
  286. // GetActiveSheetIndex provides a function to get active sheet index of the
  287. // spreadsheet. If not found the active sheet will be return integer 0.
  288. func (f *File) GetActiveSheetIndex() (index int) {
  289. var sheetID = f.getActiveSheetID()
  290. wb := f.workbookReader()
  291. if wb != nil {
  292. for idx, sheet := range wb.Sheets.Sheet {
  293. if sheet.SheetID == sheetID {
  294. index = idx
  295. }
  296. }
  297. }
  298. return
  299. }
  300. // getActiveSheetID provides a function to get active sheet ID of the
  301. // spreadsheet. If not found the active sheet will be return integer 0.
  302. func (f *File) getActiveSheetID() int {
  303. wb := f.workbookReader()
  304. if wb != nil {
  305. if wb.BookViews != nil && len(wb.BookViews.WorkBookView) > 0 {
  306. activeTab := wb.BookViews.WorkBookView[0].ActiveTab
  307. if len(wb.Sheets.Sheet) > activeTab && wb.Sheets.Sheet[activeTab].SheetID != 0 {
  308. return wb.Sheets.Sheet[activeTab].SheetID
  309. }
  310. }
  311. if len(wb.Sheets.Sheet) >= 1 {
  312. return wb.Sheets.Sheet[0].SheetID
  313. }
  314. }
  315. return 0
  316. }
  317. // SetSheetName provides a function to set the worksheet name by given old and
  318. // new worksheet names. Maximum 31 characters are allowed in sheet title and
  319. // this function only changes the name of the sheet and will not update the
  320. // sheet name in the formula or reference associated with the cell. So there
  321. // may be problem formula error or reference missing.
  322. func (f *File) SetSheetName(oldName, newName string) {
  323. oldName = trimSheetName(oldName)
  324. newName = trimSheetName(newName)
  325. if newName == oldName {
  326. return
  327. }
  328. content := f.workbookReader()
  329. for k, v := range content.Sheets.Sheet {
  330. if v.Name == oldName {
  331. content.Sheets.Sheet[k].Name = newName
  332. f.sheetMap[newName] = f.sheetMap[oldName]
  333. delete(f.sheetMap, oldName)
  334. }
  335. }
  336. }
  337. // getSheetNameByID provides a function to get worksheet name of the
  338. // spreadsheet by given worksheet ID. If given sheet ID is invalid, will
  339. // return an empty string.
  340. func (f *File) getSheetNameByID(ID int) string {
  341. wb := f.workbookReader()
  342. if wb == nil || ID < 1 {
  343. return ""
  344. }
  345. for _, sheet := range wb.Sheets.Sheet {
  346. if ID == sheet.SheetID {
  347. return sheet.Name
  348. }
  349. }
  350. return ""
  351. }
  352. // GetSheetName provides a function to get the sheet name of the workbook by
  353. // the given sheet index. If the given sheet index is invalid, it will return
  354. // an empty string.
  355. func (f *File) GetSheetName(index int) (name string) {
  356. for idx, sheet := range f.GetSheetList() {
  357. if idx == index {
  358. name = sheet
  359. }
  360. }
  361. return
  362. }
  363. // getSheetID provides a function to get worksheet ID of the spreadsheet by
  364. // given sheet name. If given worksheet name is invalid, will return an
  365. // integer type value -1.
  366. func (f *File) getSheetID(name string) int {
  367. var ID = -1
  368. for sheetID, sheet := range f.GetSheetMap() {
  369. if sheet == trimSheetName(name) {
  370. ID = sheetID
  371. }
  372. }
  373. return ID
  374. }
  375. // GetSheetIndex provides a function to get a sheet index of the workbook by
  376. // the given sheet name. If the given sheet name is invalid or sheet doesn't
  377. // exist, it will return an integer type value -1.
  378. func (f *File) GetSheetIndex(name string) int {
  379. var idx = -1
  380. for index, sheet := range f.GetSheetList() {
  381. if sheet == trimSheetName(name) {
  382. idx = index
  383. }
  384. }
  385. return idx
  386. }
  387. // GetSheetMap provides a function to get worksheets, chart sheets, dialog
  388. // sheets ID and name map of the workbook. For example:
  389. //
  390. // f, err := excelize.OpenFile("Book1.xlsx")
  391. // if err != nil {
  392. // return
  393. // }
  394. // for index, name := range f.GetSheetMap() {
  395. // fmt.Println(index, name)
  396. // }
  397. //
  398. func (f *File) GetSheetMap() map[int]string {
  399. wb := f.workbookReader()
  400. sheetMap := map[int]string{}
  401. if wb != nil {
  402. for _, sheet := range wb.Sheets.Sheet {
  403. sheetMap[sheet.SheetID] = sheet.Name
  404. }
  405. }
  406. return sheetMap
  407. }
  408. // GetSheetList provides a function to get worksheets, chart sheets, and
  409. // dialog sheets name list of the workbook.
  410. func (f *File) GetSheetList() (list []string) {
  411. wb := f.workbookReader()
  412. if wb != nil {
  413. for _, sheet := range wb.Sheets.Sheet {
  414. list = append(list, sheet.Name)
  415. }
  416. }
  417. return
  418. }
  419. // getSheetMap provides a function to get worksheet name and XML file path map
  420. // of the spreadsheet.
  421. func (f *File) getSheetMap() map[string]string {
  422. maps := map[string]string{}
  423. for _, v := range f.workbookReader().Sheets.Sheet {
  424. for _, rel := range f.relsReader(f.getWorkbookRelsPath()).Relationships {
  425. if rel.ID == v.ID {
  426. // Construct a target XML as xl/worksheets/sheet%d by split
  427. // path, compatible with different types of relative paths in
  428. // workbook.xml.rels, for example: worksheets/sheet%d.xml
  429. // and /xl/worksheets/sheet%d.xml
  430. path := filepath.ToSlash(strings.TrimPrefix(
  431. strings.Replace(filepath.Clean(fmt.Sprintf("%s/%s", filepath.Dir(f.getWorkbookPath()), rel.Target)), "\\", "/", -1), "/"))
  432. if strings.HasPrefix(rel.Target, "/") {
  433. path = filepath.ToSlash(strings.TrimPrefix(strings.Replace(filepath.Clean(rel.Target), "\\", "/", -1), "/"))
  434. }
  435. if _, ok := f.XLSX[path]; ok {
  436. maps[v.Name] = path
  437. }
  438. }
  439. }
  440. }
  441. return maps
  442. }
  443. // SetSheetBackground provides a function to set background picture by given
  444. // worksheet name and file path.
  445. func (f *File) SetSheetBackground(sheet, picture string) error {
  446. var err error
  447. // Check picture exists first.
  448. if _, err = os.Stat(picture); os.IsNotExist(err) {
  449. return err
  450. }
  451. ext, ok := supportImageTypes[path.Ext(picture)]
  452. if !ok {
  453. return errors.New("unsupported image extension")
  454. }
  455. file, _ := ioutil.ReadFile(picture)
  456. name := f.addMedia(file, ext)
  457. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(f.sheetMap[trimSheetName(sheet)], "xl/worksheets/") + ".rels"
  458. rID := f.addRels(sheetRels, SourceRelationshipImage, strings.Replace(name, "xl", "..", 1), "")
  459. f.addSheetPicture(sheet, rID)
  460. f.addSheetNameSpace(sheet, SourceRelationship)
  461. f.setContentTypePartImageExtensions()
  462. return err
  463. }
  464. // DeleteSheet provides a function to delete worksheet in a workbook by given
  465. // worksheet name. Use this method with caution, which will affect changes in
  466. // references such as formulas, charts, and so on. If there is any referenced
  467. // value of the deleted worksheet, it will cause a file error when you open it.
  468. // This function will be invalid when only the one worksheet is left.
  469. func (f *File) DeleteSheet(name string) {
  470. if f.SheetCount == 1 || f.GetSheetIndex(name) == -1 {
  471. return
  472. }
  473. sheetName := trimSheetName(name)
  474. wb := f.workbookReader()
  475. wbRels := f.relsReader(f.getWorkbookRelsPath())
  476. activeSheetName := f.GetSheetName(f.GetActiveSheetIndex())
  477. deleteSheetID := f.getSheetID(name)
  478. // Delete and adjust defined names
  479. if wb.DefinedNames != nil {
  480. for idx := 0; idx < len(wb.DefinedNames.DefinedName); idx++ {
  481. dn := wb.DefinedNames.DefinedName[idx]
  482. if dn.LocalSheetID != nil {
  483. sheetID := *dn.LocalSheetID + 1
  484. if sheetID == deleteSheetID {
  485. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
  486. idx--
  487. } else if sheetID > deleteSheetID {
  488. wb.DefinedNames.DefinedName[idx].LocalSheetID = intPtr(*dn.LocalSheetID - 1)
  489. }
  490. }
  491. }
  492. }
  493. for idx, sheet := range wb.Sheets.Sheet {
  494. if sheet.Name == sheetName {
  495. wb.Sheets.Sheet = append(wb.Sheets.Sheet[:idx], wb.Sheets.Sheet[idx+1:]...)
  496. var sheetXML, rels string
  497. if wbRels != nil {
  498. for _, rel := range wbRels.Relationships {
  499. if rel.ID == sheet.ID {
  500. sheetXML = fmt.Sprintf("xl/%s", rel.Target)
  501. pathInfo := strings.Split(rel.Target, "/")
  502. if len(pathInfo) == 2 {
  503. rels = fmt.Sprintf("xl/%s/_rels/%s.rels", pathInfo[0], pathInfo[1])
  504. }
  505. }
  506. }
  507. }
  508. target := f.deleteSheetFromWorkbookRels(sheet.ID)
  509. f.deleteSheetFromContentTypes(target)
  510. f.deleteCalcChain(sheet.SheetID, "")
  511. delete(f.sheetMap, sheetName)
  512. delete(f.XLSX, sheetXML)
  513. delete(f.XLSX, rels)
  514. delete(f.Relationships, rels)
  515. delete(f.Sheet, sheetXML)
  516. delete(f.xmlAttr, sheetXML)
  517. f.SheetCount--
  518. }
  519. }
  520. f.SetActiveSheet(f.GetSheetIndex(activeSheetName))
  521. }
  522. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  523. // relationships by given relationships ID in the file workbook.xml.rels.
  524. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  525. content := f.relsReader(f.getWorkbookRelsPath())
  526. for k, v := range content.Relationships {
  527. if v.ID == rID {
  528. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  529. return v.Target
  530. }
  531. }
  532. return ""
  533. }
  534. // deleteSheetFromContentTypes provides a function to remove worksheet
  535. // relationships by given target name in the file [Content_Types].xml.
  536. func (f *File) deleteSheetFromContentTypes(target string) {
  537. content := f.contentTypesReader()
  538. for k, v := range content.Overrides {
  539. if v.PartName == "/xl/"+target {
  540. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  541. }
  542. }
  543. }
  544. // CopySheet provides a function to duplicate a worksheet by gave source and
  545. // target worksheet index. Note that currently doesn't support duplicate
  546. // workbooks that contain tables, charts or pictures. For Example:
  547. //
  548. // // Sheet1 already exists...
  549. // index := f.NewSheet("Sheet2")
  550. // err := f.CopySheet(1, index)
  551. // return err
  552. //
  553. func (f *File) CopySheet(from, to int) error {
  554. if from < 0 || to < 0 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  555. return errors.New("invalid worksheet index")
  556. }
  557. return f.copySheet(from, to)
  558. }
  559. // copySheet provides a function to duplicate a worksheet by gave source and
  560. // target worksheet name.
  561. func (f *File) copySheet(from, to int) error {
  562. fromSheet := f.GetSheetName(from)
  563. sheet, err := f.workSheetReader(fromSheet)
  564. if err != nil {
  565. return err
  566. }
  567. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  568. toSheetID := strconv.Itoa(f.getSheetID(f.GetSheetName(to)))
  569. path := "xl/worksheets/sheet" + toSheetID + ".xml"
  570. if len(worksheet.SheetViews.SheetView) > 0 {
  571. worksheet.SheetViews.SheetView[0].TabSelected = false
  572. }
  573. worksheet.Drawing = nil
  574. worksheet.TableParts = nil
  575. worksheet.PageSetUp = nil
  576. f.Sheet[path] = worksheet
  577. toRels := "xl/worksheets/_rels/sheet" + toSheetID + ".xml.rels"
  578. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(f.getSheetID(fromSheet)) + ".xml.rels"
  579. _, ok := f.XLSX[fromRels]
  580. if ok {
  581. f.XLSX[toRels] = f.XLSX[fromRels]
  582. }
  583. fromSheetXMLPath := f.sheetMap[trimSheetName(fromSheet)]
  584. fromSheetAttr := f.xmlAttr[fromSheetXMLPath]
  585. f.xmlAttr[path] = fromSheetAttr
  586. return err
  587. }
  588. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  589. // name. A workbook must contain at least one visible worksheet. If the given
  590. // worksheet has been activated, this setting will be invalidated. Sheet state
  591. // values as defined by https://docs.microsoft.com/en-us/dotnet/api/documentformat.openxml.spreadsheet.sheetstatevalues
  592. //
  593. // visible
  594. // hidden
  595. // veryHidden
  596. //
  597. // For example, hide Sheet1:
  598. //
  599. // err := f.SetSheetVisible("Sheet1", false)
  600. //
  601. func (f *File) SetSheetVisible(name string, visible bool) error {
  602. name = trimSheetName(name)
  603. content := f.workbookReader()
  604. if visible {
  605. for k, v := range content.Sheets.Sheet {
  606. if v.Name == name {
  607. content.Sheets.Sheet[k].State = ""
  608. }
  609. }
  610. return nil
  611. }
  612. count := 0
  613. for _, v := range content.Sheets.Sheet {
  614. if v.State != "hidden" {
  615. count++
  616. }
  617. }
  618. for k, v := range content.Sheets.Sheet {
  619. xlsx, err := f.workSheetReader(v.Name)
  620. if err != nil {
  621. return err
  622. }
  623. tabSelected := false
  624. if len(xlsx.SheetViews.SheetView) > 0 {
  625. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  626. }
  627. if v.Name == name && count > 1 && !tabSelected {
  628. content.Sheets.Sheet[k].State = "hidden"
  629. }
  630. }
  631. return nil
  632. }
  633. // parseFormatPanesSet provides a function to parse the panes settings.
  634. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  635. format := formatPanes{}
  636. err := json.Unmarshal([]byte(formatSet), &format)
  637. return &format, err
  638. }
  639. // SetPanes provides a function to create and remove freeze panes and split panes
  640. // by given worksheet name and panes format set.
  641. //
  642. // activePane defines the pane that is active. The possible values for this
  643. // attribute are defined in the following table:
  644. //
  645. // Enumeration Value | Description
  646. // --------------------------------+-------------------------------------------------------------
  647. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  648. // | splits are applied.
  649. // |
  650. // | This value is also used when only a horizontal split has
  651. // | been applied, dividing the pane into upper and lower
  652. // | regions. In that case, this value specifies the bottom
  653. // | pane.
  654. // |
  655. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  656. // | splits are applied.
  657. // |
  658. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  659. // | are applied.
  660. // |
  661. // | This value is also used when only a horizontal split has
  662. // | been applied, dividing the pane into upper and lower
  663. // | regions. In that case, this value specifies the top pane.
  664. // |
  665. // | This value is also used when only a vertical split has
  666. // | been applied, dividing the pane into right and left
  667. // | regions. In that case, this value specifies the left pane
  668. // |
  669. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  670. // | splits are applied.
  671. // |
  672. // | This value is also used when only a vertical split has
  673. // | been applied, dividing the pane into right and left
  674. // | regions. In that case, this value specifies the right
  675. // | pane.
  676. //
  677. // Pane state type is restricted to the values supported currently listed in the following table:
  678. //
  679. // Enumeration Value | Description
  680. // --------------------------------+-------------------------------------------------------------
  681. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  682. // | this state, when the panes are unfrozen again, a single
  683. // | pane results, with no split.
  684. // |
  685. // | In this state, the split bars are not adjustable.
  686. // |
  687. // split (Split) | Panes are split, but not frozen. In this state, the split
  688. // | bars are adjustable by the user.
  689. //
  690. // x_split (Horizontal Split Position): Horizontal position of the split, in
  691. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  692. // indicates the number of columns visible in the top pane.
  693. //
  694. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  695. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  696. // number of rows visible in the left pane. The possible values for this
  697. // attribute are defined by the W3C XML Schema double datatype.
  698. //
  699. // top_left_cell: Location of the top left visible cell in the bottom right pane
  700. // (when in Left-To-Right mode).
  701. //
  702. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  703. // set of ranges.
  704. //
  705. // An example of how to freeze column A in the Sheet1 and set the active cell on
  706. // Sheet1!K16:
  707. //
  708. // f.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":1,"y_split":0,"top_left_cell":"B1","active_pane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`)
  709. //
  710. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  711. // ranges on Sheet1!A11:XFD11:
  712. //
  713. // f.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"top_left_cell":"A34","active_pane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`)
  714. //
  715. // An example of how to create split panes in the Sheet1 and set the active cell
  716. // on Sheet1!J60:
  717. //
  718. // f.SetPanes("Sheet1", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"top_left_cell":"N57","active_pane":"bottomLeft","panes":[{"sqref":"I36","active_cell":"I36"},{"sqref":"G33","active_cell":"G33","pane":"topRight"},{"sqref":"J60","active_cell":"J60","pane":"bottomLeft"},{"sqref":"O60","active_cell":"O60","pane":"bottomRight"}]}`)
  719. //
  720. // An example of how to unfreeze and remove all panes on Sheet1:
  721. //
  722. // f.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  723. //
  724. func (f *File) SetPanes(sheet, panes string) error {
  725. fs, _ := parseFormatPanesSet(panes)
  726. ws, err := f.workSheetReader(sheet)
  727. if err != nil {
  728. return err
  729. }
  730. p := &xlsxPane{
  731. ActivePane: fs.ActivePane,
  732. TopLeftCell: fs.TopLeftCell,
  733. XSplit: float64(fs.XSplit),
  734. YSplit: float64(fs.YSplit),
  735. }
  736. if fs.Freeze {
  737. p.State = "frozen"
  738. }
  739. ws.SheetViews.SheetView[len(ws.SheetViews.SheetView)-1].Pane = p
  740. if !(fs.Freeze) && !(fs.Split) {
  741. if len(ws.SheetViews.SheetView) > 0 {
  742. ws.SheetViews.SheetView[len(ws.SheetViews.SheetView)-1].Pane = nil
  743. }
  744. }
  745. s := []*xlsxSelection{}
  746. for _, p := range fs.Panes {
  747. s = append(s, &xlsxSelection{
  748. ActiveCell: p.ActiveCell,
  749. Pane: p.Pane,
  750. SQRef: p.SQRef,
  751. })
  752. }
  753. ws.SheetViews.SheetView[len(ws.SheetViews.SheetView)-1].Selection = s
  754. return err
  755. }
  756. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  757. // name. For example, get visible state of Sheet1:
  758. //
  759. // f.GetSheetVisible("Sheet1")
  760. //
  761. func (f *File) GetSheetVisible(name string) bool {
  762. content := f.workbookReader()
  763. visible := false
  764. for k, v := range content.Sheets.Sheet {
  765. if v.Name == trimSheetName(name) {
  766. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  767. visible = true
  768. }
  769. }
  770. }
  771. return visible
  772. }
  773. // SearchSheet provides a function to get coordinates by given worksheet name,
  774. // cell value, and regular expression. The function doesn't support searching
  775. // on the calculated result, formatted numbers and conditional lookup
  776. // currently. If it is a merged cell, it will return the coordinates of the
  777. // upper left corner of the merged area.
  778. //
  779. // An example of search the coordinates of the value of "100" on Sheet1:
  780. //
  781. // result, err := f.SearchSheet("Sheet1", "100")
  782. //
  783. // An example of search the coordinates where the numerical value in the range
  784. // of "0-9" of Sheet1 is described:
  785. //
  786. // result, err := f.SearchSheet("Sheet1", "[0-9]", true)
  787. //
  788. func (f *File) SearchSheet(sheet, value string, reg ...bool) ([]string, error) {
  789. var (
  790. regSearch bool
  791. result []string
  792. )
  793. for _, r := range reg {
  794. regSearch = r
  795. }
  796. name, ok := f.sheetMap[trimSheetName(sheet)]
  797. if !ok {
  798. return result, ErrSheetNotExist{sheet}
  799. }
  800. if f.Sheet[name] != nil {
  801. // flush data
  802. output, _ := xml.Marshal(f.Sheet[name])
  803. f.saveFileList(name, f.replaceNameSpaceBytes(name, output))
  804. }
  805. return f.searchSheet(name, value, regSearch)
  806. }
  807. // searchSheet provides a function to get coordinates by given worksheet name,
  808. // cell value, and regular expression.
  809. func (f *File) searchSheet(name, value string, regSearch bool) (result []string, err error) {
  810. var (
  811. cellName, inElement string
  812. cellCol, row int
  813. d *xlsxSST
  814. )
  815. d = f.sharedStringsReader()
  816. decoder := f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
  817. for {
  818. var token xml.Token
  819. token, err = decoder.Token()
  820. if err != nil || token == nil {
  821. if err == io.EOF {
  822. err = nil
  823. }
  824. break
  825. }
  826. switch xmlElement := token.(type) {
  827. case xml.StartElement:
  828. inElement = xmlElement.Name.Local
  829. if inElement == "row" {
  830. row, err = attrValToInt("r", xmlElement.Attr)
  831. if err != nil {
  832. return
  833. }
  834. }
  835. if inElement == "c" {
  836. colCell := xlsxC{}
  837. _ = decoder.DecodeElement(&colCell, &xmlElement)
  838. val, _ := colCell.getValueFrom(f, d)
  839. if regSearch {
  840. regex := regexp.MustCompile(value)
  841. if !regex.MatchString(val) {
  842. continue
  843. }
  844. } else {
  845. if val != value {
  846. continue
  847. }
  848. }
  849. cellCol, _, err = CellNameToCoordinates(colCell.R)
  850. if err != nil {
  851. return result, err
  852. }
  853. cellName, err = CoordinatesToCellName(cellCol, row)
  854. if err != nil {
  855. return result, err
  856. }
  857. result = append(result, cellName)
  858. }
  859. default:
  860. }
  861. }
  862. return
  863. }
  864. // attrValToInt provides a function to convert the local names to an integer
  865. // by given XML attributes and specified names.
  866. func attrValToInt(name string, attrs []xml.Attr) (val int, err error) {
  867. for _, attr := range attrs {
  868. if attr.Name.Local == name {
  869. val, err = strconv.Atoi(attr.Value)
  870. if err != nil {
  871. return
  872. }
  873. }
  874. }
  875. return
  876. }
  877. // SetHeaderFooter provides a function to set headers and footers by given
  878. // worksheet name and the control characters.
  879. //
  880. // Headers and footers are specified using the following settings fields:
  881. //
  882. // Fields | Description
  883. // ------------------+-----------------------------------------------------------
  884. // AlignWithMargins | Align header footer margins with page margins
  885. // DifferentFirst | Different first-page header and footer indicator
  886. // DifferentOddEven | Different odd and even page headers and footers indicator
  887. // ScaleWithDoc | Scale header and footer with document scaling
  888. // OddFooter | Odd Page Footer
  889. // OddHeader | Odd Header
  890. // EvenFooter | Even Page Footer
  891. // EvenHeader | Even Page Header
  892. // FirstFooter | First Page Footer
  893. // FirstHeader | First Page Header
  894. //
  895. // The following formatting codes can be used in 6 string type fields:
  896. // OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
  897. //
  898. // Formatting Code | Description
  899. // ------------------------+-------------------------------------------------------------------------
  900. // && | The character "&"
  901. // |
  902. // &font-size | Size of the text font, where font-size is a decimal font size in points
  903. // |
  904. // &"font name,font type" | A text font-name string, font name, and a text font-type string,
  905. // | font type
  906. // |
  907. // &"-,Regular" | Regular text format. Toggles bold and italic modes to off
  908. // |
  909. // &A | Current worksheet's tab name
  910. // |
  911. // &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off
  912. // |
  913. // &D | Current date
  914. // |
  915. // &C | Center section
  916. // |
  917. // &E | Double-underline text format
  918. // |
  919. // &F | Current workbook's file name
  920. // |
  921. // &G | Drawing object as background
  922. // |
  923. // &H | Shadow text format
  924. // |
  925. // &I or &"-,Italic" | Italic text format
  926. // |
  927. // &K | Text font color
  928. // |
  929. // | An RGB Color is specified as RRGGBB
  930. // |
  931. // | A Theme Color is specified as TTSNNN where TT is the theme color Id,
  932. // | S is either "+" or "-" of the tint/shade value, and NNN is the
  933. // | tint/shade value
  934. // |
  935. // &L | Left section
  936. // |
  937. // &N | Total number of pages
  938. // |
  939. // &O | Outline text format
  940. // |
  941. // &P[[+|-]n] | Without the optional suffix, the current page number in decimal
  942. // |
  943. // &R | Right section
  944. // |
  945. // &S | Strikethrough text format
  946. // |
  947. // &T | Current time
  948. // |
  949. // &U | Single-underline text format. If double-underline mode is on, the next
  950. // | occurrence in a section specifier toggles double-underline mode to off;
  951. // | otherwise, it toggles single-underline mode, from off to on, or vice
  952. // | versa. The default mode is off
  953. // |
  954. // &X | Superscript text format
  955. // |
  956. // &Y | Subscript text format
  957. // |
  958. // &Z | Current workbook's file path
  959. //
  960. // For example:
  961. //
  962. // err := f.SetHeaderFooter("Sheet1", &excelize.FormatHeaderFooter{
  963. // DifferentFirst: true,
  964. // DifferentOddEven: true,
  965. // OddHeader: "&R&P",
  966. // OddFooter: "&C&F",
  967. // EvenHeader: "&L&P",
  968. // EvenFooter: "&L&D&R&T",
  969. // FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  970. // })
  971. //
  972. // This example shows:
  973. //
  974. // - The first page has its own header and footer
  975. //
  976. // - Odd and even-numbered pages have different headers and footers
  977. //
  978. // - Current page number in the right section of odd-page headers
  979. //
  980. // - Current workbook's file name in the center section of odd-page footers
  981. //
  982. // - Current page number in the left section of even-page headers
  983. //
  984. // - Current date in the left section and the current time in the right section
  985. // of even-page footers
  986. //
  987. // - The text "Center Bold Header" on the first line of the center section of
  988. // the first page, and the date on the second line of the center section of
  989. // that same page
  990. //
  991. // - No footer on the first page
  992. //
  993. func (f *File) SetHeaderFooter(sheet string, settings *FormatHeaderFooter) error {
  994. ws, err := f.workSheetReader(sheet)
  995. if err != nil {
  996. return err
  997. }
  998. if settings == nil {
  999. ws.HeaderFooter = nil
  1000. return err
  1001. }
  1002. v := reflect.ValueOf(*settings)
  1003. // Check 6 string type fields: OddHeader, OddFooter, EvenHeader, EvenFooter,
  1004. // FirstFooter, FirstHeader
  1005. for i := 4; i < v.NumField()-1; i++ {
  1006. if v.Field(i).Len() >= 255 {
  1007. return fmt.Errorf("field %s must be less than 255 characters", v.Type().Field(i).Name)
  1008. }
  1009. }
  1010. ws.HeaderFooter = &xlsxHeaderFooter{
  1011. AlignWithMargins: settings.AlignWithMargins,
  1012. DifferentFirst: settings.DifferentFirst,
  1013. DifferentOddEven: settings.DifferentOddEven,
  1014. ScaleWithDoc: settings.ScaleWithDoc,
  1015. OddHeader: settings.OddHeader,
  1016. OddFooter: settings.OddFooter,
  1017. EvenHeader: settings.EvenHeader,
  1018. EvenFooter: settings.EvenFooter,
  1019. FirstFooter: settings.FirstFooter,
  1020. FirstHeader: settings.FirstHeader,
  1021. }
  1022. return err
  1023. }
  1024. // ProtectSheet provides a function to prevent other users from accidentally
  1025. // or deliberately changing, moving, or deleting data in a worksheet. For
  1026. // example, protect Sheet1 with protection settings:
  1027. //
  1028. // err := f.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  1029. // Password: "password",
  1030. // EditScenarios: false,
  1031. // })
  1032. //
  1033. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) error {
  1034. ws, err := f.workSheetReader(sheet)
  1035. if err != nil {
  1036. return err
  1037. }
  1038. if settings == nil {
  1039. settings = &FormatSheetProtection{
  1040. EditObjects: true,
  1041. EditScenarios: true,
  1042. SelectLockedCells: true,
  1043. }
  1044. }
  1045. ws.SheetProtection = &xlsxSheetProtection{
  1046. AutoFilter: settings.AutoFilter,
  1047. DeleteColumns: settings.DeleteColumns,
  1048. DeleteRows: settings.DeleteRows,
  1049. FormatCells: settings.FormatCells,
  1050. FormatColumns: settings.FormatColumns,
  1051. FormatRows: settings.FormatRows,
  1052. InsertColumns: settings.InsertColumns,
  1053. InsertHyperlinks: settings.InsertHyperlinks,
  1054. InsertRows: settings.InsertRows,
  1055. Objects: settings.EditObjects,
  1056. PivotTables: settings.PivotTables,
  1057. Scenarios: settings.EditScenarios,
  1058. SelectLockedCells: settings.SelectLockedCells,
  1059. SelectUnlockedCells: settings.SelectUnlockedCells,
  1060. Sheet: true,
  1061. Sort: settings.Sort,
  1062. }
  1063. if settings.Password != "" {
  1064. ws.SheetProtection.Password = genSheetPasswd(settings.Password)
  1065. }
  1066. return err
  1067. }
  1068. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  1069. func (f *File) UnprotectSheet(sheet string) error {
  1070. ws, err := f.workSheetReader(sheet)
  1071. if err != nil {
  1072. return err
  1073. }
  1074. ws.SheetProtection = nil
  1075. return err
  1076. }
  1077. // trimSheetName provides a function to trim invaild characters by given worksheet
  1078. // name.
  1079. func trimSheetName(name string) string {
  1080. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  1081. r := make([]rune, 0, 31)
  1082. for _, v := range name {
  1083. switch v {
  1084. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  1085. continue
  1086. default:
  1087. r = append(r, v)
  1088. }
  1089. if len(r) == 31 {
  1090. break
  1091. }
  1092. }
  1093. name = string(r)
  1094. }
  1095. return name
  1096. }
  1097. // PageLayoutOption is an option of a page layout of a worksheet. See
  1098. // SetPageLayout().
  1099. type PageLayoutOption interface {
  1100. setPageLayout(layout *xlsxPageSetUp)
  1101. }
  1102. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  1103. type PageLayoutOptionPtr interface {
  1104. PageLayoutOption
  1105. getPageLayout(layout *xlsxPageSetUp)
  1106. }
  1107. type (
  1108. // BlackAndWhite specified print black and white.
  1109. BlackAndWhite bool
  1110. // FirstPageNumber specified the first printed page number. If no value is
  1111. // specified, then 'automatic' is assumed.
  1112. FirstPageNumber uint
  1113. // PageLayoutOrientation defines the orientation of page layout for a
  1114. // worksheet.
  1115. PageLayoutOrientation string
  1116. // PageLayoutPaperSize defines the paper size of the worksheet.
  1117. PageLayoutPaperSize int
  1118. // FitToHeight specified the number of vertical pages to fit on.
  1119. FitToHeight int
  1120. // FitToWidth specified the number of horizontal pages to fit on.
  1121. FitToWidth int
  1122. // PageLayoutScale defines the print scaling. This attribute is restricted
  1123. // to values ranging from 10 (10%) to 400 (400%). This setting is
  1124. // overridden when fitToWidth and/or fitToHeight are in use.
  1125. PageLayoutScale uint
  1126. )
  1127. const (
  1128. // OrientationPortrait indicates page layout orientation id portrait.
  1129. OrientationPortrait = "portrait"
  1130. // OrientationLandscape indicates page layout orientation id landscape.
  1131. OrientationLandscape = "landscape"
  1132. )
  1133. // setPageLayout provides a method to set the print black and white for the
  1134. // worksheet.
  1135. func (p BlackAndWhite) setPageLayout(ps *xlsxPageSetUp) {
  1136. ps.BlackAndWhite = bool(p)
  1137. }
  1138. // getPageLayout provides a method to get the print black and white for the
  1139. // worksheet.
  1140. func (p *BlackAndWhite) getPageLayout(ps *xlsxPageSetUp) {
  1141. if ps == nil {
  1142. *p = false
  1143. return
  1144. }
  1145. *p = BlackAndWhite(ps.BlackAndWhite)
  1146. }
  1147. // setPageLayout provides a method to set the first printed page number for
  1148. // the worksheet.
  1149. func (p FirstPageNumber) setPageLayout(ps *xlsxPageSetUp) {
  1150. if 0 < uint(p) {
  1151. ps.FirstPageNumber = uint(p)
  1152. ps.UseFirstPageNumber = true
  1153. }
  1154. }
  1155. // getPageLayout provides a method to get the first printed page number for
  1156. // the worksheet.
  1157. func (p *FirstPageNumber) getPageLayout(ps *xlsxPageSetUp) {
  1158. if ps == nil || ps.FirstPageNumber == 0 || !ps.UseFirstPageNumber {
  1159. *p = 1
  1160. return
  1161. }
  1162. *p = FirstPageNumber(ps.FirstPageNumber)
  1163. }
  1164. // setPageLayout provides a method to set the orientation for the worksheet.
  1165. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  1166. ps.Orientation = string(o)
  1167. }
  1168. // getPageLayout provides a method to get the orientation for the worksheet.
  1169. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  1170. // Excel default: portrait
  1171. if ps == nil || ps.Orientation == "" {
  1172. *o = OrientationPortrait
  1173. return
  1174. }
  1175. *o = PageLayoutOrientation(ps.Orientation)
  1176. }
  1177. // setPageLayout provides a method to set the paper size for the worksheet.
  1178. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  1179. ps.PaperSize = int(p)
  1180. }
  1181. // getPageLayout provides a method to get the paper size for the worksheet.
  1182. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  1183. // Excel default: 1
  1184. if ps == nil || ps.PaperSize == 0 {
  1185. *p = 1
  1186. return
  1187. }
  1188. *p = PageLayoutPaperSize(ps.PaperSize)
  1189. }
  1190. // setPageLayout provides a method to set the fit to height for the worksheet.
  1191. func (p FitToHeight) setPageLayout(ps *xlsxPageSetUp) {
  1192. if int(p) > 0 {
  1193. ps.FitToHeight = int(p)
  1194. }
  1195. }
  1196. // getPageLayout provides a method to get the fit to height for the worksheet.
  1197. func (p *FitToHeight) getPageLayout(ps *xlsxPageSetUp) {
  1198. if ps == nil || ps.FitToHeight == 0 {
  1199. *p = 1
  1200. return
  1201. }
  1202. *p = FitToHeight(ps.FitToHeight)
  1203. }
  1204. // setPageLayout provides a method to set the fit to width for the worksheet.
  1205. func (p FitToWidth) setPageLayout(ps *xlsxPageSetUp) {
  1206. if int(p) > 0 {
  1207. ps.FitToWidth = int(p)
  1208. }
  1209. }
  1210. // getPageLayout provides a method to get the fit to width for the worksheet.
  1211. func (p *FitToWidth) getPageLayout(ps *xlsxPageSetUp) {
  1212. if ps == nil || ps.FitToWidth == 0 {
  1213. *p = 1
  1214. return
  1215. }
  1216. *p = FitToWidth(ps.FitToWidth)
  1217. }
  1218. // setPageLayout provides a method to set the scale for the worksheet.
  1219. func (p PageLayoutScale) setPageLayout(ps *xlsxPageSetUp) {
  1220. if 10 <= uint(p) && uint(p) <= 400 {
  1221. ps.Scale = uint(p)
  1222. }
  1223. }
  1224. // getPageLayout provides a method to get the scale for the worksheet.
  1225. func (p *PageLayoutScale) getPageLayout(ps *xlsxPageSetUp) {
  1226. if ps == nil || ps.Scale < 10 || ps.Scale > 400 {
  1227. *p = 100
  1228. return
  1229. }
  1230. *p = PageLayoutScale(ps.Scale)
  1231. }
  1232. // SetPageLayout provides a function to sets worksheet page layout.
  1233. //
  1234. // Available options:
  1235. //
  1236. // BlackAndWhite(bool)
  1237. // FirstPageNumber(uint)
  1238. // PageLayoutOrientation(string)
  1239. // PageLayoutPaperSize(int)
  1240. // FitToHeight(int)
  1241. // FitToWidth(int)
  1242. // PageLayoutScale(uint)
  1243. //
  1244. // The following shows the paper size sorted by excelize index number:
  1245. //
  1246. // Index | Paper Size
  1247. // -------+-----------------------------------------------
  1248. // 1 | Letter paper (8.5 in. by 11 in.)
  1249. // 2 | Letter small paper (8.5 in. by 11 in.)
  1250. // 3 | Tabloid paper (11 in. by 17 in.)
  1251. // 4 | Ledger paper (17 in. by 11 in.)
  1252. // 5 | Legal paper (8.5 in. by 14 in.)
  1253. // 6 | Statement paper (5.5 in. by 8.5 in.)
  1254. // 7 | Executive paper (7.25 in. by 10.5 in.)
  1255. // 8 | A3 paper (297 mm by 420 mm)
  1256. // 9 | A4 paper (210 mm by 297 mm)
  1257. // 10 | A4 small paper (210 mm by 297 mm)
  1258. // 11 | A5 paper (148 mm by 210 mm)
  1259. // 12 | B4 paper (250 mm by 353 mm)
  1260. // 13 | B5 paper (176 mm by 250 mm)
  1261. // 14 | Folio paper (8.5 in. by 13 in.)
  1262. // 15 | Quarto paper (215 mm by 275 mm)
  1263. // 16 | Standard paper (10 in. by 14 in.)
  1264. // 17 | Standard paper (11 in. by 17 in.)
  1265. // 18 | Note paper (8.5 in. by 11 in.)
  1266. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  1267. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  1268. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  1269. // 22 | #12 envelope (4.75 in. by 11 in.)
  1270. // 23 | #14 envelope (5 in. by 11.5 in.)
  1271. // 24 | C paper (17 in. by 22 in.)
  1272. // 25 | D paper (22 in. by 34 in.)
  1273. // 26 | E paper (34 in. by 44 in.)
  1274. // 27 | DL envelope (110 mm by 220 mm)
  1275. // 28 | C5 envelope (162 mm by 229 mm)
  1276. // 29 | C3 envelope (324 mm by 458 mm)
  1277. // 30 | C4 envelope (229 mm by 324 mm)
  1278. // 31 | C6 envelope (114 mm by 162 mm)
  1279. // 32 | C65 envelope (114 mm by 229 mm)
  1280. // 33 | B4 envelope (250 mm by 353 mm)
  1281. // 34 | B5 envelope (176 mm by 250 mm)
  1282. // 35 | B6 envelope (176 mm by 125 mm)
  1283. // 36 | Italy envelope (110 mm by 230 mm)
  1284. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  1285. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  1286. // 39 | US standard fanfold (14.875 in. by 11 in.)
  1287. // 40 | German standard fanfold (8.5 in. by 12 in.)
  1288. // 41 | German legal fanfold (8.5 in. by 13 in.)
  1289. // 42 | ISO B4 (250 mm by 353 mm)
  1290. // 43 | Japanese postcard (100 mm by 148 mm)
  1291. // 44 | Standard paper (9 in. by 11 in.)
  1292. // 45 | Standard paper (10 in. by 11 in.)
  1293. // 46 | Standard paper (15 in. by 11 in.)
  1294. // 47 | Invite envelope (220 mm by 220 mm)
  1295. // 50 | Letter extra paper (9.275 in. by 12 in.)
  1296. // 51 | Legal extra paper (9.275 in. by 15 in.)
  1297. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  1298. // 53 | A4 extra paper (236 mm by 322 mm)
  1299. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  1300. // 55 | A4 transverse paper (210 mm by 297 mm)
  1301. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  1302. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  1303. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  1304. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  1305. // 60 | A4 plus paper (210 mm by 330 mm)
  1306. // 61 | A5 transverse paper (148 mm by 210 mm)
  1307. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  1308. // 63 | A3 extra paper (322 mm by 445 mm)
  1309. // 64 | A5 extra paper (174 mm by 235 mm)
  1310. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  1311. // 66 | A2 paper (420 mm by 594 mm)
  1312. // 67 | A3 transverse paper (297 mm by 420 mm)
  1313. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  1314. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  1315. // 70 | A6 (105 mm x 148 mm)
  1316. // 71 | Japanese Envelope Kaku #2
  1317. // 72 | Japanese Envelope Kaku #3
  1318. // 73 | Japanese Envelope Chou #3
  1319. // 74 | Japanese Envelope Chou #4
  1320. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  1321. // 76 | A3 Rotated (420 mm x 297 mm)
  1322. // 77 | A4 Rotated (297 mm x 210 mm)
  1323. // 78 | A5 Rotated (210 mm x 148 mm)
  1324. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  1325. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  1326. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  1327. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  1328. // 83 | A6 Rotated (148 mm x 105 mm)
  1329. // 84 | Japanese Envelope Kaku #2 Rotated
  1330. // 85 | Japanese Envelope Kaku #3 Rotated
  1331. // 86 | Japanese Envelope Chou #3 Rotated
  1332. // 87 | Japanese Envelope Chou #4 Rotated
  1333. // 88 | B6 (JIS) (128 mm x 182 mm)
  1334. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  1335. // 90 | (12 in x 11 in)
  1336. // 91 | Japanese Envelope You #4
  1337. // 92 | Japanese Envelope You #4 Rotated
  1338. // 93 | PRC 16K (146 mm x 215 mm)
  1339. // 94 | PRC 32K (97 mm x 151 mm)
  1340. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  1341. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  1342. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  1343. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  1344. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  1345. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  1346. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  1347. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  1348. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  1349. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  1350. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  1351. // 106 | PRC 16K Rotated
  1352. // 107 | PRC 32K Rotated
  1353. // 108 | PRC 32K(Big) Rotated
  1354. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  1355. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  1356. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  1357. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  1358. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  1359. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  1360. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  1361. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  1362. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  1363. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  1364. //
  1365. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  1366. s, err := f.workSheetReader(sheet)
  1367. if err != nil {
  1368. return err
  1369. }
  1370. ps := s.PageSetUp
  1371. if ps == nil {
  1372. ps = new(xlsxPageSetUp)
  1373. s.PageSetUp = ps
  1374. }
  1375. for _, opt := range opts {
  1376. opt.setPageLayout(ps)
  1377. }
  1378. return err
  1379. }
  1380. // GetPageLayout provides a function to gets worksheet page layout.
  1381. //
  1382. // Available options:
  1383. // PageLayoutOrientation(string)
  1384. // PageLayoutPaperSize(int)
  1385. // FitToHeight(int)
  1386. // FitToWidth(int)
  1387. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  1388. s, err := f.workSheetReader(sheet)
  1389. if err != nil {
  1390. return err
  1391. }
  1392. ps := s.PageSetUp
  1393. for _, opt := range opts {
  1394. opt.getPageLayout(ps)
  1395. }
  1396. return err
  1397. }
  1398. // SetDefinedName provides a function to set the defined names of the workbook
  1399. // or worksheet. If not specified scope, the default scope is workbook.
  1400. // For example:
  1401. //
  1402. // f.SetDefinedName(&excelize.DefinedName{
  1403. // Name: "Amount",
  1404. // RefersTo: "Sheet1!$A$2:$D$5",
  1405. // Comment: "defined name comment",
  1406. // Scope: "Sheet2",
  1407. // })
  1408. //
  1409. func (f *File) SetDefinedName(definedName *DefinedName) error {
  1410. wb := f.workbookReader()
  1411. d := xlsxDefinedName{
  1412. Name: definedName.Name,
  1413. Comment: definedName.Comment,
  1414. Data: definedName.RefersTo,
  1415. }
  1416. if definedName.Scope != "" {
  1417. if sheetIndex := f.GetSheetIndex(definedName.Scope); sheetIndex >= 0 {
  1418. d.LocalSheetID = &sheetIndex
  1419. }
  1420. }
  1421. if wb.DefinedNames != nil {
  1422. for _, dn := range wb.DefinedNames.DefinedName {
  1423. var scope string
  1424. if dn.LocalSheetID != nil {
  1425. scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1426. }
  1427. if scope == definedName.Scope && dn.Name == definedName.Name {
  1428. return errors.New("the same name already exists on the scope")
  1429. }
  1430. }
  1431. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d)
  1432. return nil
  1433. }
  1434. wb.DefinedNames = &xlsxDefinedNames{
  1435. DefinedName: []xlsxDefinedName{d},
  1436. }
  1437. return nil
  1438. }
  1439. // DeleteDefinedName provides a function to delete the defined names of the
  1440. // workbook or worksheet. If not specified scope, the default scope is
  1441. // workbook. For example:
  1442. //
  1443. // f.DeleteDefinedName(&excelize.DefinedName{
  1444. // Name: "Amount",
  1445. // Scope: "Sheet2",
  1446. // })
  1447. //
  1448. func (f *File) DeleteDefinedName(definedName *DefinedName) error {
  1449. wb := f.workbookReader()
  1450. if wb.DefinedNames != nil {
  1451. for idx, dn := range wb.DefinedNames.DefinedName {
  1452. var scope string
  1453. if dn.LocalSheetID != nil {
  1454. scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1455. }
  1456. if scope == definedName.Scope && dn.Name == definedName.Name {
  1457. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
  1458. return nil
  1459. }
  1460. }
  1461. }
  1462. return errors.New("no defined name on the scope")
  1463. }
  1464. // GetDefinedName provides a function to get the defined names of the workbook
  1465. // or worksheet.
  1466. func (f *File) GetDefinedName() []DefinedName {
  1467. var definedNames []DefinedName
  1468. wb := f.workbookReader()
  1469. if wb.DefinedNames != nil {
  1470. for _, dn := range wb.DefinedNames.DefinedName {
  1471. definedName := DefinedName{
  1472. Name: dn.Name,
  1473. Comment: dn.Comment,
  1474. RefersTo: dn.Data,
  1475. Scope: "Workbook",
  1476. }
  1477. if dn.LocalSheetID != nil && *dn.LocalSheetID >= 0 {
  1478. definedName.Scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1479. }
  1480. definedNames = append(definedNames, definedName)
  1481. }
  1482. }
  1483. return definedNames
  1484. }
  1485. // GroupSheets provides a function to group worksheets by given worksheets
  1486. // name. Group worksheets must contain an active worksheet.
  1487. func (f *File) GroupSheets(sheets []string) error {
  1488. // check an active worksheet in group worksheets
  1489. var inActiveSheet bool
  1490. activeSheet := f.GetActiveSheetIndex()
  1491. sheetMap := f.GetSheetList()
  1492. for idx, sheetName := range sheetMap {
  1493. for _, s := range sheets {
  1494. if s == sheetName && idx == activeSheet {
  1495. inActiveSheet = true
  1496. }
  1497. }
  1498. }
  1499. if !inActiveSheet {
  1500. return errors.New("group worksheet must contain an active worksheet")
  1501. }
  1502. // check worksheet exists
  1503. wss := []*xlsxWorksheet{}
  1504. for _, sheet := range sheets {
  1505. worksheet, err := f.workSheetReader(sheet)
  1506. if err != nil {
  1507. return err
  1508. }
  1509. wss = append(wss, worksheet)
  1510. }
  1511. for _, ws := range wss {
  1512. sheetViews := ws.SheetViews.SheetView
  1513. if len(sheetViews) > 0 {
  1514. for idx := range sheetViews {
  1515. ws.SheetViews.SheetView[idx].TabSelected = true
  1516. }
  1517. continue
  1518. }
  1519. }
  1520. return nil
  1521. }
  1522. // UngroupSheets provides a function to ungroup worksheets.
  1523. func (f *File) UngroupSheets() error {
  1524. activeSheet := f.GetActiveSheetIndex()
  1525. for index, sheet := range f.GetSheetList() {
  1526. if activeSheet == index {
  1527. continue
  1528. }
  1529. ws, _ := f.workSheetReader(sheet)
  1530. sheetViews := ws.SheetViews.SheetView
  1531. if len(sheetViews) > 0 {
  1532. for idx := range sheetViews {
  1533. ws.SheetViews.SheetView[idx].TabSelected = false
  1534. }
  1535. }
  1536. }
  1537. return nil
  1538. }
  1539. // InsertPageBreak create a page break to determine where the printed page
  1540. // ends and where begins the next one by given worksheet name and axis, so the
  1541. // content before the page break will be printed on one page and after the
  1542. // page break on another.
  1543. func (f *File) InsertPageBreak(sheet, cell string) (err error) {
  1544. var ws *xlsxWorksheet
  1545. var row, col int
  1546. var rowBrk, colBrk = -1, -1
  1547. if ws, err = f.workSheetReader(sheet); err != nil {
  1548. return
  1549. }
  1550. if col, row, err = CellNameToCoordinates(cell); err != nil {
  1551. return
  1552. }
  1553. col--
  1554. row--
  1555. if col == row && col == 0 {
  1556. return
  1557. }
  1558. if ws.RowBreaks == nil {
  1559. ws.RowBreaks = &xlsxBreaks{}
  1560. }
  1561. if ws.ColBreaks == nil {
  1562. ws.ColBreaks = &xlsxBreaks{}
  1563. }
  1564. for idx, brk := range ws.RowBreaks.Brk {
  1565. if brk.ID == row {
  1566. rowBrk = idx
  1567. }
  1568. }
  1569. for idx, brk := range ws.ColBreaks.Brk {
  1570. if brk.ID == col {
  1571. colBrk = idx
  1572. }
  1573. }
  1574. if row != 0 && rowBrk == -1 {
  1575. ws.RowBreaks.Brk = append(ws.RowBreaks.Brk, &xlsxBrk{
  1576. ID: row,
  1577. Max: 16383,
  1578. Man: true,
  1579. })
  1580. ws.RowBreaks.ManualBreakCount++
  1581. }
  1582. if col != 0 && colBrk == -1 {
  1583. ws.ColBreaks.Brk = append(ws.ColBreaks.Brk, &xlsxBrk{
  1584. ID: col,
  1585. Max: 1048575,
  1586. Man: true,
  1587. })
  1588. ws.ColBreaks.ManualBreakCount++
  1589. }
  1590. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1591. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1592. return
  1593. }
  1594. // RemovePageBreak remove a page break by given worksheet name and axis.
  1595. func (f *File) RemovePageBreak(sheet, cell string) (err error) {
  1596. var ws *xlsxWorksheet
  1597. var row, col int
  1598. if ws, err = f.workSheetReader(sheet); err != nil {
  1599. return
  1600. }
  1601. if col, row, err = CellNameToCoordinates(cell); err != nil {
  1602. return
  1603. }
  1604. col--
  1605. row--
  1606. if col == row && col == 0 {
  1607. return
  1608. }
  1609. removeBrk := func(ID int, brks []*xlsxBrk) []*xlsxBrk {
  1610. for i, brk := range brks {
  1611. if brk.ID == ID {
  1612. brks = append(brks[:i], brks[i+1:]...)
  1613. }
  1614. }
  1615. return brks
  1616. }
  1617. if ws.RowBreaks == nil || ws.ColBreaks == nil {
  1618. return
  1619. }
  1620. rowBrks := len(ws.RowBreaks.Brk)
  1621. colBrks := len(ws.ColBreaks.Brk)
  1622. if rowBrks > 0 && rowBrks == colBrks {
  1623. ws.RowBreaks.Brk = removeBrk(row, ws.RowBreaks.Brk)
  1624. ws.ColBreaks.Brk = removeBrk(col, ws.ColBreaks.Brk)
  1625. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1626. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1627. ws.RowBreaks.ManualBreakCount--
  1628. ws.ColBreaks.ManualBreakCount--
  1629. return
  1630. }
  1631. if rowBrks > 0 && rowBrks > colBrks {
  1632. ws.RowBreaks.Brk = removeBrk(row, ws.RowBreaks.Brk)
  1633. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1634. ws.RowBreaks.ManualBreakCount--
  1635. return
  1636. }
  1637. if colBrks > 0 && colBrks > rowBrks {
  1638. ws.ColBreaks.Brk = removeBrk(col, ws.ColBreaks.Brk)
  1639. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1640. ws.ColBreaks.ManualBreakCount--
  1641. }
  1642. return
  1643. }
  1644. // relsReader provides a function to get the pointer to the structure
  1645. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1646. func (f *File) relsReader(path string) *xlsxRelationships {
  1647. var err error
  1648. if f.Relationships[path] == nil {
  1649. _, ok := f.XLSX[path]
  1650. if ok {
  1651. c := xlsxRelationships{}
  1652. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(path)))).
  1653. Decode(&c); err != nil && err != io.EOF {
  1654. log.Printf("xml decode error: %s", err)
  1655. }
  1656. f.Relationships[path] = &c
  1657. }
  1658. }
  1659. return f.Relationships[path]
  1660. }
  1661. // fillSheetData ensures there are enough rows, and columns in the chosen
  1662. // row to accept data. Missing rows are backfilled and given their row number
  1663. // Uses the last populated row as a hint for the size of the next row to add
  1664. func prepareSheetXML(ws *xlsxWorksheet, col int, row int) {
  1665. rowCount := len(ws.SheetData.Row)
  1666. sizeHint := 0
  1667. var ht float64
  1668. var customHeight bool
  1669. if ws.SheetFormatPr != nil && ws.SheetFormatPr.CustomHeight {
  1670. ht = ws.SheetFormatPr.DefaultRowHeight
  1671. customHeight = true
  1672. }
  1673. if rowCount > 0 {
  1674. sizeHint = len(ws.SheetData.Row[rowCount-1].C)
  1675. }
  1676. if rowCount < row {
  1677. // append missing rows
  1678. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1679. ws.SheetData.Row = append(ws.SheetData.Row, xlsxRow{R: rowIdx + 1, CustomHeight: customHeight, Ht: ht, C: make([]xlsxC, 0, sizeHint)})
  1680. }
  1681. }
  1682. rowData := &ws.SheetData.Row[row-1]
  1683. fillColumns(rowData, col, row)
  1684. }
  1685. // fillColumns fill cells in the column of the row as contiguous.
  1686. func fillColumns(rowData *xlsxRow, col, row int) {
  1687. cellCount := len(rowData.C)
  1688. if cellCount < col {
  1689. for colIdx := cellCount; colIdx < col; colIdx++ {
  1690. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1691. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1692. }
  1693. }
  1694. }
  1695. // makeContiguousColumns make columns in specific rows as contiguous.
  1696. func makeContiguousColumns(ws *xlsxWorksheet, fromRow, toRow, colCount int) {
  1697. for ; fromRow < toRow; fromRow++ {
  1698. rowData := &ws.SheetData.Row[fromRow-1]
  1699. fillColumns(rowData, colCount, fromRow)
  1700. }
  1701. }