sheet.go 54 KB

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