sheet.go 58 KB

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