sheet.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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 Exce™ 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.10 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 sheetID := f.getSheetID(definedName.Scope); sheetID != 0 {
  1418. sheetID--
  1419. d.LocalSheetID = &sheetID
  1420. }
  1421. }
  1422. if wb.DefinedNames != nil {
  1423. for _, dn := range wb.DefinedNames.DefinedName {
  1424. var scope string
  1425. if dn.LocalSheetID != nil {
  1426. scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1427. }
  1428. if scope == definedName.Scope && dn.Name == definedName.Name {
  1429. return errors.New("the same name already exists on the scope")
  1430. }
  1431. }
  1432. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d)
  1433. return nil
  1434. }
  1435. wb.DefinedNames = &xlsxDefinedNames{
  1436. DefinedName: []xlsxDefinedName{d},
  1437. }
  1438. return nil
  1439. }
  1440. // DeleteDefinedName provides a function to delete the defined names of the
  1441. // workbook or worksheet. If not specified scope, the default scope is
  1442. // workbook. For example:
  1443. //
  1444. // f.DeleteDefinedName(&excelize.DefinedName{
  1445. // Name: "Amount",
  1446. // Scope: "Sheet2",
  1447. // })
  1448. //
  1449. func (f *File) DeleteDefinedName(definedName *DefinedName) error {
  1450. wb := f.workbookReader()
  1451. if wb.DefinedNames != nil {
  1452. for idx, dn := range wb.DefinedNames.DefinedName {
  1453. var scope string
  1454. if dn.LocalSheetID != nil {
  1455. scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1456. }
  1457. if scope == definedName.Scope && dn.Name == definedName.Name {
  1458. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
  1459. return nil
  1460. }
  1461. }
  1462. }
  1463. return errors.New("no defined name on the scope")
  1464. }
  1465. // GetDefinedName provides a function to get the defined names of the workbook
  1466. // or worksheet.
  1467. func (f *File) GetDefinedName() []DefinedName {
  1468. var definedNames []DefinedName
  1469. wb := f.workbookReader()
  1470. if wb.DefinedNames != nil {
  1471. for _, dn := range wb.DefinedNames.DefinedName {
  1472. definedName := DefinedName{
  1473. Name: dn.Name,
  1474. Comment: dn.Comment,
  1475. RefersTo: dn.Data,
  1476. Scope: "Workbook",
  1477. }
  1478. if dn.LocalSheetID != nil && *dn.LocalSheetID >= 0 {
  1479. definedName.Scope = f.getSheetNameByID(*dn.LocalSheetID + 1)
  1480. }
  1481. definedNames = append(definedNames, definedName)
  1482. }
  1483. }
  1484. return definedNames
  1485. }
  1486. // GroupSheets provides a function to group worksheets by given worksheets
  1487. // name. Group worksheets must contain an active worksheet.
  1488. func (f *File) GroupSheets(sheets []string) error {
  1489. // check an active worksheet in group worksheets
  1490. var inActiveSheet bool
  1491. activeSheet := f.GetActiveSheetIndex()
  1492. sheetMap := f.GetSheetList()
  1493. for idx, sheetName := range sheetMap {
  1494. for _, s := range sheets {
  1495. if s == sheetName && idx == activeSheet {
  1496. inActiveSheet = true
  1497. }
  1498. }
  1499. }
  1500. if !inActiveSheet {
  1501. return errors.New("group worksheet must contain an active worksheet")
  1502. }
  1503. // check worksheet exists
  1504. wss := []*xlsxWorksheet{}
  1505. for _, sheet := range sheets {
  1506. worksheet, err := f.workSheetReader(sheet)
  1507. if err != nil {
  1508. return err
  1509. }
  1510. wss = append(wss, worksheet)
  1511. }
  1512. for _, ws := range wss {
  1513. sheetViews := ws.SheetViews.SheetView
  1514. if len(sheetViews) > 0 {
  1515. for idx := range sheetViews {
  1516. ws.SheetViews.SheetView[idx].TabSelected = true
  1517. }
  1518. continue
  1519. }
  1520. }
  1521. return nil
  1522. }
  1523. // UngroupSheets provides a function to ungroup worksheets.
  1524. func (f *File) UngroupSheets() error {
  1525. activeSheet := f.GetActiveSheetIndex()
  1526. for index, sheet := range f.GetSheetList() {
  1527. if activeSheet == index {
  1528. continue
  1529. }
  1530. ws, _ := f.workSheetReader(sheet)
  1531. sheetViews := ws.SheetViews.SheetView
  1532. if len(sheetViews) > 0 {
  1533. for idx := range sheetViews {
  1534. ws.SheetViews.SheetView[idx].TabSelected = false
  1535. }
  1536. }
  1537. }
  1538. return nil
  1539. }
  1540. // InsertPageBreak create a page break to determine where the printed page
  1541. // ends and where begins the next one by given worksheet name and axis, so the
  1542. // content before the page break will be printed on one page and after the
  1543. // page break on another.
  1544. func (f *File) InsertPageBreak(sheet, cell string) (err error) {
  1545. var ws *xlsxWorksheet
  1546. var row, col int
  1547. var rowBrk, colBrk = -1, -1
  1548. if ws, err = f.workSheetReader(sheet); err != nil {
  1549. return
  1550. }
  1551. if col, row, err = CellNameToCoordinates(cell); err != nil {
  1552. return
  1553. }
  1554. col--
  1555. row--
  1556. if col == row && col == 0 {
  1557. return
  1558. }
  1559. if ws.RowBreaks == nil {
  1560. ws.RowBreaks = &xlsxBreaks{}
  1561. }
  1562. if ws.ColBreaks == nil {
  1563. ws.ColBreaks = &xlsxBreaks{}
  1564. }
  1565. for idx, brk := range ws.RowBreaks.Brk {
  1566. if brk.ID == row {
  1567. rowBrk = idx
  1568. }
  1569. }
  1570. for idx, brk := range ws.ColBreaks.Brk {
  1571. if brk.ID == col {
  1572. colBrk = idx
  1573. }
  1574. }
  1575. if row != 0 && rowBrk == -1 {
  1576. ws.RowBreaks.Brk = append(ws.RowBreaks.Brk, &xlsxBrk{
  1577. ID: row,
  1578. Max: 16383,
  1579. Man: true,
  1580. })
  1581. ws.RowBreaks.ManualBreakCount++
  1582. }
  1583. if col != 0 && colBrk == -1 {
  1584. ws.ColBreaks.Brk = append(ws.ColBreaks.Brk, &xlsxBrk{
  1585. ID: col,
  1586. Max: 1048575,
  1587. Man: true,
  1588. })
  1589. ws.ColBreaks.ManualBreakCount++
  1590. }
  1591. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1592. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1593. return
  1594. }
  1595. // RemovePageBreak remove a page break by given worksheet name and axis.
  1596. func (f *File) RemovePageBreak(sheet, cell string) (err error) {
  1597. var ws *xlsxWorksheet
  1598. var row, col int
  1599. if ws, err = f.workSheetReader(sheet); err != nil {
  1600. return
  1601. }
  1602. if col, row, err = CellNameToCoordinates(cell); err != nil {
  1603. return
  1604. }
  1605. col--
  1606. row--
  1607. if col == row && col == 0 {
  1608. return
  1609. }
  1610. removeBrk := func(ID int, brks []*xlsxBrk) []*xlsxBrk {
  1611. for i, brk := range brks {
  1612. if brk.ID == ID {
  1613. brks = append(brks[:i], brks[i+1:]...)
  1614. }
  1615. }
  1616. return brks
  1617. }
  1618. if ws.RowBreaks == nil || ws.ColBreaks == nil {
  1619. return
  1620. }
  1621. rowBrks := len(ws.RowBreaks.Brk)
  1622. colBrks := len(ws.ColBreaks.Brk)
  1623. if rowBrks > 0 && rowBrks == colBrks {
  1624. ws.RowBreaks.Brk = removeBrk(row, ws.RowBreaks.Brk)
  1625. ws.ColBreaks.Brk = removeBrk(col, ws.ColBreaks.Brk)
  1626. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1627. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1628. ws.RowBreaks.ManualBreakCount--
  1629. ws.ColBreaks.ManualBreakCount--
  1630. return
  1631. }
  1632. if rowBrks > 0 && rowBrks > colBrks {
  1633. ws.RowBreaks.Brk = removeBrk(row, ws.RowBreaks.Brk)
  1634. ws.RowBreaks.Count = len(ws.RowBreaks.Brk)
  1635. ws.RowBreaks.ManualBreakCount--
  1636. return
  1637. }
  1638. if colBrks > 0 && colBrks > rowBrks {
  1639. ws.ColBreaks.Brk = removeBrk(col, ws.ColBreaks.Brk)
  1640. ws.ColBreaks.Count = len(ws.ColBreaks.Brk)
  1641. ws.ColBreaks.ManualBreakCount--
  1642. }
  1643. return
  1644. }
  1645. // relsReader provides a function to get the pointer to the structure
  1646. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1647. func (f *File) relsReader(path string) *xlsxRelationships {
  1648. var err error
  1649. if f.Relationships[path] == nil {
  1650. _, ok := f.XLSX[path]
  1651. if ok {
  1652. c := xlsxRelationships{}
  1653. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(path)))).
  1654. Decode(&c); err != nil && err != io.EOF {
  1655. log.Printf("xml decode error: %s", err)
  1656. }
  1657. f.Relationships[path] = &c
  1658. }
  1659. }
  1660. return f.Relationships[path]
  1661. }
  1662. // fillSheetData ensures there are enough rows, and columns in the chosen
  1663. // row to accept data. Missing rows are backfilled and given their row number
  1664. // Uses the last populated row as a hint for the size of the next row to add
  1665. func prepareSheetXML(ws *xlsxWorksheet, col int, row int) {
  1666. rowCount := len(ws.SheetData.Row)
  1667. sizeHint := 0
  1668. var ht float64
  1669. var customHeight bool
  1670. if ws.SheetFormatPr != nil && ws.SheetFormatPr.CustomHeight {
  1671. ht = ws.SheetFormatPr.DefaultRowHeight
  1672. customHeight = true
  1673. }
  1674. if rowCount > 0 {
  1675. sizeHint = len(ws.SheetData.Row[rowCount-1].C)
  1676. }
  1677. if rowCount < row {
  1678. // append missing rows
  1679. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1680. ws.SheetData.Row = append(ws.SheetData.Row, xlsxRow{R: rowIdx + 1, CustomHeight: customHeight, Ht: ht, C: make([]xlsxC, 0, sizeHint)})
  1681. }
  1682. }
  1683. rowData := &ws.SheetData.Row[row-1]
  1684. fillColumns(rowData, col, row)
  1685. }
  1686. // fillColumns fill cells in the column of the row as contiguous.
  1687. func fillColumns(rowData *xlsxRow, col, row int) {
  1688. cellCount := len(rowData.C)
  1689. if cellCount < col {
  1690. for colIdx := cellCount; colIdx < col; colIdx++ {
  1691. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1692. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1693. }
  1694. }
  1695. }
  1696. // makeContiguousColumns make columns in specific rows as contiguous.
  1697. func makeContiguousColumns(ws *xlsxWorksheet, fromRow, toRow, colCount int) {
  1698. for ; fromRow < toRow; fromRow++ {
  1699. rowData := &ws.SheetData.Row[fromRow-1]
  1700. fillColumns(rowData, colCount, fromRow)
  1701. }
  1702. }