sheet.go 56 KB

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