sheet.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. // Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
  7. // Microsoft Excel™ 2007 and later. Support save file without losing original
  8. // charts of XLSX. This library needs Go version 1.8 or later.
  9. package excelize
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "encoding/xml"
  14. "errors"
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "reflect"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "unicode/utf8"
  24. "github.com/mohae/deepcopy"
  25. )
  26. // NewSheet provides function to create a new sheet by given worksheet name.
  27. // When creating a new XLSX file, the default sheet will be created. Returns
  28. // the number of sheets in the workbook (file) after appending the new sheet.
  29. func (f *File) NewSheet(name string) int {
  30. // Check if the worksheet already exists
  31. if f.GetSheetIndex(name) != 0 {
  32. return f.SheetCount
  33. }
  34. f.DeleteSheet(name)
  35. f.SheetCount++
  36. wb := f.workbookReader()
  37. sheetID := 0
  38. for _, v := range wb.Sheets.Sheet {
  39. if v.SheetID > sheetID {
  40. sheetID = v.SheetID
  41. }
  42. }
  43. sheetID++
  44. // Update docProps/app.xml
  45. f.setAppXML()
  46. // Update [Content_Types].xml
  47. f.setContentTypes(sheetID)
  48. // Create new sheet /xl/worksheets/sheet%d.xml
  49. f.setSheet(sheetID, name)
  50. // Update xl/_rels/workbook.xml.rels
  51. rID := f.addXlsxWorkbookRels(sheetID)
  52. // Update xl/workbook.xml
  53. f.setWorkbook(name, sheetID, rID)
  54. return sheetID
  55. }
  56. // contentTypesReader provides a function to get the pointer to the
  57. // [Content_Types].xml structure after deserialization.
  58. func (f *File) contentTypesReader() *xlsxTypes {
  59. if f.ContentTypes == nil {
  60. var content xlsxTypes
  61. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("[Content_Types].xml")), &content)
  62. f.ContentTypes = &content
  63. }
  64. return f.ContentTypes
  65. }
  66. // contentTypesWriter provides a function to save [Content_Types].xml after
  67. // serialize structure.
  68. func (f *File) contentTypesWriter() {
  69. if f.ContentTypes != nil {
  70. output, _ := xml.Marshal(f.ContentTypes)
  71. f.saveFileList("[Content_Types].xml", output)
  72. }
  73. }
  74. // workbookReader provides a function to get the pointer to the xl/workbook.xml
  75. // structure after deserialization.
  76. func (f *File) workbookReader() *xlsxWorkbook {
  77. if f.WorkBook == nil {
  78. var content xlsxWorkbook
  79. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/workbook.xml")), &content)
  80. f.WorkBook = &content
  81. }
  82. return f.WorkBook
  83. }
  84. // workBookWriter provides a function to save xl/workbook.xml after serialize
  85. // structure.
  86. func (f *File) workBookWriter() {
  87. if f.WorkBook != nil {
  88. output, _ := xml.Marshal(f.WorkBook)
  89. f.saveFileList("xl/workbook.xml", replaceRelationshipsBytes(replaceRelationshipsNameSpaceBytes(output)))
  90. }
  91. }
  92. // workSheetWriter provides a function to save xl/worksheets/sheet%d.xml after
  93. // serialize structure.
  94. func (f *File) workSheetWriter() {
  95. for p, sheet := range f.Sheet {
  96. if sheet != nil {
  97. for k, v := range sheet.SheetData.Row {
  98. f.Sheet[p].SheetData.Row[k].C = trimCell(v.C)
  99. }
  100. output, _ := xml.Marshal(sheet)
  101. f.saveFileList(p, replaceRelationshipsBytes(replaceWorkSheetsRelationshipsNameSpaceBytes(output)))
  102. ok := f.checked[p]
  103. if ok {
  104. f.checked[p] = false
  105. }
  106. }
  107. }
  108. }
  109. // trimCell provides a function to trim blank cells which created by completeCol.
  110. func trimCell(column []xlsxC) []xlsxC {
  111. col := make([]xlsxC, len(column))
  112. i := 0
  113. for _, c := range column {
  114. if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
  115. col[i] = c
  116. i++
  117. }
  118. }
  119. return col[0:i]
  120. }
  121. // setContentTypes provides a function to read and update property of contents
  122. // type of XLSX.
  123. func (f *File) setContentTypes(index int) {
  124. content := f.contentTypesReader()
  125. content.Overrides = append(content.Overrides, xlsxOverride{
  126. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  127. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  128. })
  129. }
  130. // setSheet provides a function to update sheet property by given index.
  131. func (f *File) setSheet(index int, name string) {
  132. var xlsx xlsxWorksheet
  133. xlsx.Dimension.Ref = "A1"
  134. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  135. WorkbookViewID: 0,
  136. })
  137. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  138. f.sheetMap[trimSheetName(name)] = path
  139. f.Sheet[path] = &xlsx
  140. }
  141. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  142. // allowed in sheet title.
  143. func (f *File) setWorkbook(name string, sheetID, rid int) {
  144. content := f.workbookReader()
  145. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  146. Name: trimSheetName(name),
  147. SheetID: sheetID,
  148. ID: "rId" + strconv.Itoa(rid),
  149. })
  150. }
  151. // workbookRelsReader provides a function to read and unmarshal workbook
  152. // relationships of XLSX file.
  153. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  154. if f.WorkBookRels == nil {
  155. var content xlsxWorkbookRels
  156. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  157. f.WorkBookRels = &content
  158. }
  159. return f.WorkBookRels
  160. }
  161. // workBookRelsWriter provides a function to save xl/_rels/workbook.xml.rels after
  162. // serialize structure.
  163. func (f *File) workBookRelsWriter() {
  164. if f.WorkBookRels != nil {
  165. output, _ := xml.Marshal(f.WorkBookRels)
  166. f.saveFileList("xl/_rels/workbook.xml.rels", output)
  167. }
  168. }
  169. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  170. func (f *File) addXlsxWorkbookRels(sheet int) int {
  171. content := f.workbookRelsReader()
  172. rID := 0
  173. for _, v := range content.Relationships {
  174. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  175. if t > rID {
  176. rID = t
  177. }
  178. }
  179. rID++
  180. ID := bytes.Buffer{}
  181. ID.WriteString("rId")
  182. ID.WriteString(strconv.Itoa(rID))
  183. target := bytes.Buffer{}
  184. target.WriteString("worksheets/sheet")
  185. target.WriteString(strconv.Itoa(sheet))
  186. target.WriteString(".xml")
  187. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  188. ID: ID.String(),
  189. Target: target.String(),
  190. Type: SourceRelationshipWorkSheet,
  191. })
  192. return rID
  193. }
  194. // setAppXML update docProps/app.xml file of XML.
  195. func (f *File) setAppXML() {
  196. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  197. }
  198. // replaceRelationshipsBytes; Some tools that read XLSX files have very strict
  199. // requirements about the structure of the input XML. This function is a
  200. // horrible hack to fix that after the XML marshalling is completed.
  201. func replaceRelationshipsBytes(content []byte) []byte {
  202. oldXmlns := []byte(`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships`)
  203. newXmlns := []byte("r")
  204. return bytes.Replace(content, oldXmlns, newXmlns, -1)
  205. }
  206. // replaceRelationshipsNameSpaceBytes; Some tools that read XLSX files have
  207. // very strict requirements about the structure of the input XML. In
  208. // particular both Numbers on the Mac and SAS dislike inline XML namespace
  209. // declarations, or namespace prefixes that don't match the ones that Excel
  210. // itself uses. This is a problem because the Go XML library doesn't multiple
  211. // namespace declarations in a single element of a document. This function is
  212. // a horrible hack to fix that after the XML marshalling is completed.
  213. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  214. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  215. newXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`)
  216. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  217. }
  218. // SetActiveSheet provides function to set default active worksheet of XLSX by
  219. // given index. Note that active index is different from the index returned by
  220. // function GetSheetMap(). It should be greater than 0 and less than total
  221. // worksheet numbers.
  222. func (f *File) SetActiveSheet(index int) {
  223. if index < 1 {
  224. index = 1
  225. }
  226. wb := f.workbookReader()
  227. for activeTab, sheet := range wb.Sheets.Sheet {
  228. if sheet.SheetID == index {
  229. if len(wb.BookViews.WorkBookView) > 0 {
  230. wb.BookViews.WorkBookView[0].ActiveTab = activeTab
  231. } else {
  232. wb.BookViews.WorkBookView = append(wb.BookViews.WorkBookView, xlsxWorkBookView{
  233. ActiveTab: activeTab,
  234. })
  235. }
  236. }
  237. }
  238. for idx, name := range f.GetSheetMap() {
  239. xlsx, _ := f.workSheetReader(name)
  240. if len(xlsx.SheetViews.SheetView) > 0 {
  241. xlsx.SheetViews.SheetView[0].TabSelected = false
  242. }
  243. if index == idx {
  244. if len(xlsx.SheetViews.SheetView) > 0 {
  245. xlsx.SheetViews.SheetView[0].TabSelected = true
  246. } else {
  247. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  248. TabSelected: true,
  249. })
  250. }
  251. }
  252. }
  253. }
  254. // GetActiveSheetIndex provides a function to get active sheet index of the
  255. // XLSX. If not found the active sheet will be return integer 0.
  256. func (f *File) GetActiveSheetIndex() int {
  257. for idx, name := range f.GetSheetMap() {
  258. xlsx, _ := f.workSheetReader(name)
  259. for _, sheetView := range xlsx.SheetViews.SheetView {
  260. if sheetView.TabSelected {
  261. return idx
  262. }
  263. }
  264. }
  265. return 0
  266. }
  267. // SetSheetName provides a function to set the worksheet name be given old and
  268. // new worksheet name. Maximum 31 characters are allowed in sheet title and
  269. // this function only changes the name of the sheet and will not update the
  270. // sheet name in the formula or reference associated with the cell. So there
  271. // may be problem formula error or reference missing.
  272. func (f *File) SetSheetName(oldName, newName string) {
  273. oldName = trimSheetName(oldName)
  274. newName = trimSheetName(newName)
  275. content := f.workbookReader()
  276. for k, v := range content.Sheets.Sheet {
  277. if v.Name == oldName {
  278. content.Sheets.Sheet[k].Name = newName
  279. f.sheetMap[newName] = f.sheetMap[oldName]
  280. delete(f.sheetMap, oldName)
  281. }
  282. }
  283. }
  284. // GetSheetName provides a function to get worksheet name of XLSX by given
  285. // worksheet index. If given sheet index is invalid, will return an empty
  286. // string.
  287. func (f *File) GetSheetName(index int) string {
  288. content := f.workbookReader()
  289. rels := f.workbookRelsReader()
  290. for _, rel := range rels.Relationships {
  291. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  292. if rID == index {
  293. for _, v := range content.Sheets.Sheet {
  294. if v.ID == rel.ID {
  295. return v.Name
  296. }
  297. }
  298. }
  299. }
  300. return ""
  301. }
  302. // GetSheetIndex provides a function to get worksheet index of XLSX by given sheet
  303. // name. If given worksheet name is invalid, will return an integer type value
  304. // 0.
  305. func (f *File) GetSheetIndex(name string) int {
  306. content := f.workbookReader()
  307. rels := f.workbookRelsReader()
  308. for _, v := range content.Sheets.Sheet {
  309. if v.Name == name {
  310. for _, rel := range rels.Relationships {
  311. if v.ID == rel.ID {
  312. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  313. return rID
  314. }
  315. }
  316. }
  317. }
  318. return 0
  319. }
  320. // GetSheetMap provides a function to get worksheet name and index map of XLSX.
  321. // For example:
  322. //
  323. // f, err := excelize.OpenFile("./Book1.xlsx")
  324. // if err != nil {
  325. // return
  326. // }
  327. // for index, name := range f.GetSheetMap() {
  328. // fmt.Println(index, name)
  329. // }
  330. //
  331. func (f *File) GetSheetMap() map[int]string {
  332. content := f.workbookReader()
  333. rels := f.workbookRelsReader()
  334. sheetMap := map[int]string{}
  335. for _, v := range content.Sheets.Sheet {
  336. for _, rel := range rels.Relationships {
  337. relStr := strings.SplitN(rel.Target, "worksheets/sheet", 2)
  338. if rel.ID == v.ID && len(relStr) == 2 {
  339. rID, _ := strconv.Atoi(strings.TrimSuffix(relStr[1], ".xml"))
  340. sheetMap[rID] = v.Name
  341. }
  342. }
  343. }
  344. return sheetMap
  345. }
  346. // getSheetMap provides a function to get worksheet name and XML file path map of
  347. // XLSX.
  348. func (f *File) getSheetMap() map[string]string {
  349. maps := make(map[string]string)
  350. for idx, name := range f.GetSheetMap() {
  351. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  352. }
  353. return maps
  354. }
  355. // SetSheetBackground provides a function to set background picture by given
  356. // worksheet name and file path.
  357. func (f *File) SetSheetBackground(sheet, picture string) error {
  358. var err error
  359. // Check picture exists first.
  360. if _, err = os.Stat(picture); os.IsNotExist(err) {
  361. return err
  362. }
  363. ext, ok := supportImageTypes[path.Ext(picture)]
  364. if !ok {
  365. return errors.New("unsupported image extension")
  366. }
  367. file, _ := ioutil.ReadFile(picture)
  368. name := f.addMedia(file, ext)
  369. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, strings.Replace(name, "xl", "..", 1), "")
  370. f.addSheetPicture(sheet, rID)
  371. f.setContentTypePartImageExtensions()
  372. return err
  373. }
  374. // DeleteSheet provides a function to delete worksheet in a workbook by given
  375. // worksheet name. Use this method with caution, which will affect changes in
  376. // references such as formulas, charts, and so on. If there is any referenced
  377. // value of the deleted worksheet, it will cause a file error when you open it.
  378. // This function will be invalid when only the one worksheet is left.
  379. func (f *File) DeleteSheet(name string) {
  380. content := f.workbookReader()
  381. for k, v := range content.Sheets.Sheet {
  382. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  383. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  384. sheet := "xl/worksheets/sheet" + strconv.Itoa(v.SheetID) + ".xml"
  385. rels := "xl/worksheets/_rels/sheet" + strconv.Itoa(v.SheetID) + ".xml.rels"
  386. target := f.deleteSheetFromWorkbookRels(v.ID)
  387. f.deleteSheetFromContentTypes(target)
  388. f.deleteCalcChain(v.SheetID, "") // Delete CalcChain
  389. delete(f.sheetMap, name)
  390. delete(f.XLSX, sheet)
  391. delete(f.XLSX, rels)
  392. delete(f.Sheet, sheet)
  393. f.SheetCount--
  394. }
  395. }
  396. f.SetActiveSheet(len(f.GetSheetMap()))
  397. }
  398. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  399. // relationships by given relationships ID in the file
  400. // xl/_rels/workbook.xml.rels.
  401. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  402. content := f.workbookRelsReader()
  403. for k, v := range content.Relationships {
  404. if v.ID == rID {
  405. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  406. return v.Target
  407. }
  408. }
  409. return ""
  410. }
  411. // deleteSheetFromContentTypes provides a function to remove worksheet
  412. // relationships by given target name in the file [Content_Types].xml.
  413. func (f *File) deleteSheetFromContentTypes(target string) {
  414. content := f.contentTypesReader()
  415. for k, v := range content.Overrides {
  416. if v.PartName == "/xl/"+target {
  417. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  418. }
  419. }
  420. }
  421. // CopySheet provides a function to duplicate a worksheet by gave source and
  422. // target worksheet index. Note that currently doesn't support duplicate
  423. // workbooks that contain tables, charts or pictures. For Example:
  424. //
  425. // // Sheet1 already exists...
  426. // index := f.NewSheet("Sheet2")
  427. // err := f.CopySheet(1, index)
  428. // return err
  429. //
  430. func (f *File) CopySheet(from, to int) error {
  431. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  432. return errors.New("invalid worksheet index")
  433. }
  434. return f.copySheet(from, to)
  435. }
  436. // copySheet provides a function to duplicate a worksheet by gave source and
  437. // target worksheet name.
  438. func (f *File) copySheet(from, to int) error {
  439. sheet, err := f.workSheetReader(f.GetSheetName(from))
  440. if err != nil {
  441. return err
  442. }
  443. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  444. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  445. if len(worksheet.SheetViews.SheetView) > 0 {
  446. worksheet.SheetViews.SheetView[0].TabSelected = false
  447. }
  448. worksheet.Drawing = nil
  449. worksheet.TableParts = nil
  450. worksheet.PageSetUp = nil
  451. f.Sheet[path] = worksheet
  452. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  453. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  454. _, ok := f.XLSX[fromRels]
  455. if ok {
  456. f.XLSX[toRels] = f.XLSX[fromRels]
  457. }
  458. return err
  459. }
  460. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  461. // name. A workbook must contain at least one visible worksheet. If the given
  462. // worksheet has been activated, this setting will be invalidated. Sheet state
  463. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  464. //
  465. // visible
  466. // hidden
  467. // veryHidden
  468. //
  469. // For example, hide Sheet1:
  470. //
  471. // err := f.SetSheetVisible("Sheet1", false)
  472. //
  473. func (f *File) SetSheetVisible(name string, visible bool) error {
  474. name = trimSheetName(name)
  475. content := f.workbookReader()
  476. if visible {
  477. for k, v := range content.Sheets.Sheet {
  478. if v.Name == name {
  479. content.Sheets.Sheet[k].State = ""
  480. }
  481. }
  482. return nil
  483. }
  484. count := 0
  485. for _, v := range content.Sheets.Sheet {
  486. if v.State != "hidden" {
  487. count++
  488. }
  489. }
  490. for k, v := range content.Sheets.Sheet {
  491. xlsx, err := f.workSheetReader(f.GetSheetMap()[k])
  492. if err != nil {
  493. return err
  494. }
  495. tabSelected := false
  496. if len(xlsx.SheetViews.SheetView) > 0 {
  497. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  498. }
  499. if v.Name == name && count > 1 && !tabSelected {
  500. content.Sheets.Sheet[k].State = "hidden"
  501. }
  502. }
  503. return nil
  504. }
  505. // parseFormatPanesSet provides a function to parse the panes settings.
  506. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  507. format := formatPanes{}
  508. err := json.Unmarshal([]byte(formatSet), &format)
  509. return &format, err
  510. }
  511. // SetPanes provides a function to create and remove freeze panes and split panes
  512. // by given worksheet name and panes format set.
  513. //
  514. // activePane defines the pane that is active. The possible values for this
  515. // attribute are defined in the following table:
  516. //
  517. // Enumeration Value | Description
  518. // --------------------------------+-------------------------------------------------------------
  519. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  520. // | splits are applied.
  521. // |
  522. // | This value is also used when only a horizontal split has
  523. // | been applied, dividing the pane into upper and lower
  524. // | regions. In that case, this value specifies the bottom
  525. // | pane.
  526. // |
  527. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  528. // | splits are applied.
  529. // |
  530. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  531. // | are applied.
  532. // |
  533. // | This value is also used when only a horizontal split has
  534. // | been applied, dividing the pane into upper and lower
  535. // | regions. In that case, this value specifies the top pane.
  536. // |
  537. // | This value is also used when only a vertical split has
  538. // | been applied, dividing the pane into right and left
  539. // | regions. In that case, this value specifies the left pane
  540. // |
  541. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  542. // | splits are applied.
  543. // |
  544. // | This value is also used when only a vertical split has
  545. // | been applied, dividing the pane into right and left
  546. // | regions. In that case, this value specifies the right
  547. // | pane.
  548. //
  549. // Pane state type is restricted to the values supported currently listed in the following table:
  550. //
  551. // Enumeration Value | Description
  552. // --------------------------------+-------------------------------------------------------------
  553. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  554. // | this state, when the panes are unfrozen again, a single
  555. // | pane results, with no split.
  556. // |
  557. // | In this state, the split bars are not adjustable.
  558. // |
  559. // split (Split) | Panes are split, but not frozen. In this state, the split
  560. // | bars are adjustable by the user.
  561. //
  562. // x_split (Horizontal Split Position): Horizontal position of the split, in
  563. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  564. // indicates the number of columns visible in the top pane.
  565. //
  566. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  567. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  568. // number of rows visible in the left pane. The possible values for this
  569. // attribute are defined by the W3C XML Schema double datatype.
  570. //
  571. // top_left_cell: Location of the top left visible cell in the bottom right pane
  572. // (when in Left-To-Right mode).
  573. //
  574. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  575. // set of ranges.
  576. //
  577. // An example of how to freeze column A in the Sheet1 and set the active cell on
  578. // Sheet1!K16:
  579. //
  580. // 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"}]}`)
  581. //
  582. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  583. // ranges on Sheet1!A11:XFD11:
  584. //
  585. // 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"}]}`)
  586. //
  587. // An example of how to create split panes in the Sheet1 and set the active cell
  588. // on Sheet1!J60:
  589. //
  590. // 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"}]}`)
  591. //
  592. // An example of how to unfreeze and remove all panes on Sheet1:
  593. //
  594. // f.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  595. //
  596. func (f *File) SetPanes(sheet, panes string) error {
  597. fs, _ := parseFormatPanesSet(panes)
  598. xlsx, err := f.workSheetReader(sheet)
  599. if err != nil {
  600. return err
  601. }
  602. p := &xlsxPane{
  603. ActivePane: fs.ActivePane,
  604. TopLeftCell: fs.TopLeftCell,
  605. XSplit: float64(fs.XSplit),
  606. YSplit: float64(fs.YSplit),
  607. }
  608. if fs.Freeze {
  609. p.State = "frozen"
  610. }
  611. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  612. if !(fs.Freeze) && !(fs.Split) {
  613. if len(xlsx.SheetViews.SheetView) > 0 {
  614. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  615. }
  616. }
  617. s := []*xlsxSelection{}
  618. for _, p := range fs.Panes {
  619. s = append(s, &xlsxSelection{
  620. ActiveCell: p.ActiveCell,
  621. Pane: p.Pane,
  622. SQRef: p.SQRef,
  623. })
  624. }
  625. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  626. return err
  627. }
  628. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  629. // name. For example, get visible state of Sheet1:
  630. //
  631. // f.GetSheetVisible("Sheet1")
  632. //
  633. func (f *File) GetSheetVisible(name string) bool {
  634. content := f.workbookReader()
  635. visible := false
  636. for k, v := range content.Sheets.Sheet {
  637. if v.Name == trimSheetName(name) {
  638. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  639. visible = true
  640. }
  641. }
  642. }
  643. return visible
  644. }
  645. // SearchSheet provides a function to get coordinates by given worksheet name,
  646. // cell value, and regular expression. The function doesn't support searching
  647. // on the calculated result, formatted numbers and conditional lookup
  648. // currently. If it is a merged cell, it will return the coordinates of the
  649. // upper left corner of the merged area.
  650. //
  651. // An example of search the coordinates of the value of "100" on Sheet1:
  652. //
  653. // result, err := f.SearchSheet("Sheet1", "100")
  654. //
  655. // An example of search the coordinates where the numerical value in the range
  656. // of "0-9" of Sheet1 is described:
  657. //
  658. // result, err := f.SearchSheet("Sheet1", "[0-9]", true)
  659. //
  660. func (f *File) SearchSheet(sheet, value string, reg ...bool) ([]string, error) {
  661. var (
  662. regSearch bool
  663. result []string
  664. inElement string
  665. r xlsxRow
  666. )
  667. for _, r := range reg {
  668. regSearch = r
  669. }
  670. xlsx, err := f.workSheetReader(sheet)
  671. if err != nil {
  672. return result, err
  673. }
  674. name, ok := f.sheetMap[trimSheetName(sheet)]
  675. if !ok {
  676. return result, nil
  677. }
  678. if xlsx != nil {
  679. output, _ := xml.Marshal(f.Sheet[name])
  680. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  681. }
  682. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  683. d := f.sharedStringsReader()
  684. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  685. for {
  686. token, _ := decoder.Token()
  687. if token == nil {
  688. break
  689. }
  690. switch startElement := token.(type) {
  691. case xml.StartElement:
  692. inElement = startElement.Name.Local
  693. if inElement == "row" {
  694. r = xlsxRow{}
  695. _ = decoder.DecodeElement(&r, &startElement)
  696. for _, colCell := range r.C {
  697. val, _ := colCell.getValueFrom(f, d)
  698. if regSearch {
  699. regex := regexp.MustCompile(value)
  700. if !regex.MatchString(val) {
  701. continue
  702. }
  703. } else {
  704. if val != value {
  705. continue
  706. }
  707. }
  708. cellCol, _, err := CellNameToCoordinates(colCell.R)
  709. if err != nil {
  710. return result, err
  711. }
  712. cellName, err := CoordinatesToCellName(cellCol, r.R)
  713. if err != nil {
  714. return result, err
  715. }
  716. result = append(result, cellName)
  717. }
  718. }
  719. default:
  720. }
  721. }
  722. return result, nil
  723. }
  724. // SetHeaderFooter provides a function to set headers and footers by given
  725. // worksheet name and the control characters.
  726. //
  727. // Headers and footers are specified using the following settings fields:
  728. //
  729. // Fields | Description
  730. // ------------------+-----------------------------------------------------------
  731. // AlignWithMargins | Align header footer margins with page margins
  732. // DifferentFirst | Different first-page header and footer indicator
  733. // DifferentOddEven | Different odd and even page headers and footers indicator
  734. // ScaleWithDoc | Scale header and footer with document scaling
  735. // OddFooter | Odd Page Footer
  736. // OddHeader | Odd Header
  737. // EvenFooter | Even Page Footer
  738. // EvenHeader | Even Page Header
  739. // FirstFooter | First Page Footer
  740. // FirstHeader | First Page Header
  741. //
  742. // The following formatting codes can be used in 6 string type fields:
  743. // OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
  744. //
  745. // Formatting Code | Description
  746. // ------------------------+-------------------------------------------------------------------------
  747. // && | The character "&"
  748. // |
  749. // &font-size | Size of the text font, where font-size is a decimal font size in points
  750. // |
  751. // &"font name,font type" | A text font-name string, font name, and a text font-type string,
  752. // | font type
  753. // |
  754. // &"-,Regular" | Regular text format. Toggles bold and italic modes to off
  755. // |
  756. // &A | Current worksheet's tab name
  757. // |
  758. // &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off
  759. // |
  760. // &D | Current date
  761. // |
  762. // &C | Center section
  763. // |
  764. // &E | Double-underline text format
  765. // |
  766. // &F | Current workbook's file name
  767. // |
  768. // &G | Drawing object as background
  769. // |
  770. // &H | Shadow text format
  771. // |
  772. // &I or &"-,Italic" | Italic text format
  773. // |
  774. // &K | Text font color
  775. // |
  776. // | An RGB Color is specified as RRGGBB
  777. // |
  778. // | A Theme Color is specified as TTSNNN where TT is the theme color Id,
  779. // | S is either "+" or "-" of the tint/shade value, and NNN is the
  780. // | tint/shade value
  781. // |
  782. // &L | Left section
  783. // |
  784. // &N | Total number of pages
  785. // |
  786. // &O | Outline text format
  787. // |
  788. // &P[[+|-]n] | Without the optional suffix, the current page number in decimal
  789. // |
  790. // &R | Right section
  791. // |
  792. // &S | Strikethrough text format
  793. // |
  794. // &T | Current time
  795. // |
  796. // &U | Single-underline text format. If double-underline mode is on, the next
  797. // | occurrence in a section specifier toggles double-underline mode to off;
  798. // | otherwise, it toggles single-underline mode, from off to on, or vice
  799. // | versa. The default mode is off
  800. // |
  801. // &X | Superscript text format
  802. // |
  803. // &Y | Subscript text format
  804. // |
  805. // &Z | Current workbook's file path
  806. //
  807. // For example:
  808. //
  809. // err := f.SetHeaderFooter("Sheet1", &excelize.FormatHeaderFooter{
  810. // DifferentFirst: true,
  811. // DifferentOddEven: true,
  812. // OddHeader: "&R&P",
  813. // OddFooter: "&C&F",
  814. // EvenHeader: "&L&P",
  815. // EvenFooter: "&L&D&R&T",
  816. // FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  817. // })
  818. //
  819. // This example shows:
  820. //
  821. // - The first page has its own header and footer
  822. //
  823. // - Odd and even-numbered pages have different headers and footers
  824. //
  825. // - Current page number in the right section of odd-page headers
  826. //
  827. // - Current workbook's file name in the center section of odd-page footers
  828. //
  829. // - Current page number in the left section of even-page headers
  830. //
  831. // - Current date in the left section and the current time in the right section
  832. // of even-page footers
  833. //
  834. // - The text "Center Bold Header" on the first line of the center section of
  835. // the first page, and the date on the second line of the center section of
  836. // that same page
  837. //
  838. // - No footer on the first page
  839. //
  840. func (f *File) SetHeaderFooter(sheet string, settings *FormatHeaderFooter) error {
  841. xlsx, err := f.workSheetReader(sheet)
  842. if err != nil {
  843. return err
  844. }
  845. if settings == nil {
  846. xlsx.HeaderFooter = nil
  847. return err
  848. }
  849. v := reflect.ValueOf(*settings)
  850. // Check 6 string type fields: OddHeader, OddFooter, EvenHeader, EvenFooter,
  851. // FirstFooter, FirstHeader
  852. for i := 4; i < v.NumField()-1; i++ {
  853. if v.Field(i).Len() >= 255 {
  854. return fmt.Errorf("field %s must be less than 255 characters", v.Type().Field(i).Name)
  855. }
  856. }
  857. xlsx.HeaderFooter = &xlsxHeaderFooter{
  858. AlignWithMargins: settings.AlignWithMargins,
  859. DifferentFirst: settings.DifferentFirst,
  860. DifferentOddEven: settings.DifferentOddEven,
  861. ScaleWithDoc: settings.ScaleWithDoc,
  862. OddHeader: settings.OddHeader,
  863. OddFooter: settings.OddFooter,
  864. EvenHeader: settings.EvenHeader,
  865. EvenFooter: settings.EvenFooter,
  866. FirstFooter: settings.FirstFooter,
  867. FirstHeader: settings.FirstHeader,
  868. }
  869. return err
  870. }
  871. // ProtectSheet provides a function to prevent other users from accidentally
  872. // or deliberately changing, moving, or deleting data in a worksheet. For
  873. // example, protect Sheet1 with protection settings:
  874. //
  875. // err := f.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  876. // Password: "password",
  877. // EditScenarios: false,
  878. // })
  879. //
  880. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) error {
  881. xlsx, err := f.workSheetReader(sheet)
  882. if err != nil {
  883. return err
  884. }
  885. if settings == nil {
  886. settings = &FormatSheetProtection{
  887. EditObjects: true,
  888. EditScenarios: true,
  889. SelectLockedCells: true,
  890. }
  891. }
  892. xlsx.SheetProtection = &xlsxSheetProtection{
  893. AutoFilter: settings.AutoFilter,
  894. DeleteColumns: settings.DeleteColumns,
  895. DeleteRows: settings.DeleteRows,
  896. FormatCells: settings.FormatCells,
  897. FormatColumns: settings.FormatColumns,
  898. FormatRows: settings.FormatRows,
  899. InsertColumns: settings.InsertColumns,
  900. InsertHyperlinks: settings.InsertHyperlinks,
  901. InsertRows: settings.InsertRows,
  902. Objects: settings.EditObjects,
  903. PivotTables: settings.PivotTables,
  904. Scenarios: settings.EditScenarios,
  905. SelectLockedCells: settings.SelectLockedCells,
  906. SelectUnlockedCells: settings.SelectUnlockedCells,
  907. Sheet: true,
  908. Sort: settings.Sort,
  909. }
  910. if settings.Password != "" {
  911. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  912. }
  913. return err
  914. }
  915. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  916. func (f *File) UnprotectSheet(sheet string) error {
  917. xlsx, err := f.workSheetReader(sheet)
  918. if err != nil {
  919. return err
  920. }
  921. xlsx.SheetProtection = nil
  922. return err
  923. }
  924. // trimSheetName provides a function to trim invaild characters by given worksheet
  925. // name.
  926. func trimSheetName(name string) string {
  927. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  928. r := make([]rune, 0, 31)
  929. for _, v := range name {
  930. switch v {
  931. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  932. continue
  933. default:
  934. r = append(r, v)
  935. }
  936. if len(r) == 31 {
  937. break
  938. }
  939. }
  940. name = string(r)
  941. }
  942. return name
  943. }
  944. // PageLayoutOption is an option of a page layout of a worksheet. See
  945. // SetPageLayout().
  946. type PageLayoutOption interface {
  947. setPageLayout(layout *xlsxPageSetUp)
  948. }
  949. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  950. type PageLayoutOptionPtr interface {
  951. PageLayoutOption
  952. getPageLayout(layout *xlsxPageSetUp)
  953. }
  954. type (
  955. // PageLayoutOrientation defines the orientation of page layout for a
  956. // worksheet.
  957. PageLayoutOrientation string
  958. // PageLayoutPaperSize defines the paper size of the worksheet
  959. PageLayoutPaperSize int
  960. )
  961. const (
  962. // OrientationPortrait indicates page layout orientation id portrait.
  963. OrientationPortrait = "portrait"
  964. // OrientationLandscape indicates page layout orientation id landscape.
  965. OrientationLandscape = "landscape"
  966. )
  967. // setPageLayout provides a method to set the orientation for the worksheet.
  968. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  969. ps.Orientation = string(o)
  970. }
  971. // getPageLayout provides a method to get the orientation for the worksheet.
  972. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  973. // Excel default: portrait
  974. if ps == nil || ps.Orientation == "" {
  975. *o = OrientationPortrait
  976. return
  977. }
  978. *o = PageLayoutOrientation(ps.Orientation)
  979. }
  980. // setPageLayout provides a method to set the paper size for the worksheet.
  981. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  982. ps.PaperSize = int(p)
  983. }
  984. // getPageLayout provides a method to get the paper size for the worksheet.
  985. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  986. // Excel default: 1
  987. if ps == nil || ps.PaperSize == 0 {
  988. *p = 1
  989. return
  990. }
  991. *p = PageLayoutPaperSize(ps.PaperSize)
  992. }
  993. // SetPageLayout provides a function to sets worksheet page layout.
  994. //
  995. // Available options:
  996. // PageLayoutOrientation(string)
  997. // PageLayoutPaperSize(int)
  998. //
  999. // The following shows the paper size sorted by excelize index number:
  1000. //
  1001. // Index | Paper Size
  1002. // -------+-----------------------------------------------
  1003. // 1 | Letter paper (8.5 in. by 11 in.)
  1004. // 2 | Letter small paper (8.5 in. by 11 in.)
  1005. // 3 | Tabloid paper (11 in. by 17 in.)
  1006. // 4 | Ledger paper (17 in. by 11 in.)
  1007. // 5 | Legal paper (8.5 in. by 14 in.)
  1008. // 6 | Statement paper (5.5 in. by 8.5 in.)
  1009. // 7 | Executive paper (7.25 in. by 10.5 in.)
  1010. // 8 | A3 paper (297 mm by 420 mm)
  1011. // 9 | A4 paper (210 mm by 297 mm)
  1012. // 10 | A4 small paper (210 mm by 297 mm)
  1013. // 11 | A5 paper (148 mm by 210 mm)
  1014. // 12 | B4 paper (250 mm by 353 mm)
  1015. // 13 | B5 paper (176 mm by 250 mm)
  1016. // 14 | Folio paper (8.5 in. by 13 in.)
  1017. // 15 | Quarto paper (215 mm by 275 mm)
  1018. // 16 | Standard paper (10 in. by 14 in.)
  1019. // 17 | Standard paper (11 in. by 17 in.)
  1020. // 18 | Note paper (8.5 in. by 11 in.)
  1021. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  1022. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  1023. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  1024. // 22 | #12 envelope (4.75 in. by 11 in.)
  1025. // 23 | #14 envelope (5 in. by 11.5 in.)
  1026. // 24 | C paper (17 in. by 22 in.)
  1027. // 25 | D paper (22 in. by 34 in.)
  1028. // 26 | E paper (34 in. by 44 in.)
  1029. // 27 | DL envelope (110 mm by 220 mm)
  1030. // 28 | C5 envelope (162 mm by 229 mm)
  1031. // 29 | C3 envelope (324 mm by 458 mm)
  1032. // 30 | C4 envelope (229 mm by 324 mm)
  1033. // 31 | C6 envelope (114 mm by 162 mm)
  1034. // 32 | C65 envelope (114 mm by 229 mm)
  1035. // 33 | B4 envelope (250 mm by 353 mm)
  1036. // 34 | B5 envelope (176 mm by 250 mm)
  1037. // 35 | B6 envelope (176 mm by 125 mm)
  1038. // 36 | Italy envelope (110 mm by 230 mm)
  1039. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  1040. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  1041. // 39 | US standard fanfold (14.875 in. by 11 in.)
  1042. // 40 | German standard fanfold (8.5 in. by 12 in.)
  1043. // 41 | German legal fanfold (8.5 in. by 13 in.)
  1044. // 42 | ISO B4 (250 mm by 353 mm)
  1045. // 43 | Japanese postcard (100 mm by 148 mm)
  1046. // 44 | Standard paper (9 in. by 11 in.)
  1047. // 45 | Standard paper (10 in. by 11 in.)
  1048. // 46 | Standard paper (15 in. by 11 in.)
  1049. // 47 | Invite envelope (220 mm by 220 mm)
  1050. // 50 | Letter extra paper (9.275 in. by 12 in.)
  1051. // 51 | Legal extra paper (9.275 in. by 15 in.)
  1052. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  1053. // 53 | A4 extra paper (236 mm by 322 mm)
  1054. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  1055. // 55 | A4 transverse paper (210 mm by 297 mm)
  1056. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  1057. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  1058. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  1059. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  1060. // 60 | A4 plus paper (210 mm by 330 mm)
  1061. // 61 | A5 transverse paper (148 mm by 210 mm)
  1062. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  1063. // 63 | A3 extra paper (322 mm by 445 mm)
  1064. // 64 | A5 extra paper (174 mm by 235 mm)
  1065. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  1066. // 66 | A2 paper (420 mm by 594 mm)
  1067. // 67 | A3 transverse paper (297 mm by 420 mm)
  1068. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  1069. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  1070. // 70 | A6 (105 mm x 148 mm)
  1071. // 71 | Japanese Envelope Kaku #2
  1072. // 72 | Japanese Envelope Kaku #3
  1073. // 73 | Japanese Envelope Chou #3
  1074. // 74 | Japanese Envelope Chou #4
  1075. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  1076. // 76 | A3 Rotated (420 mm x 297 mm)
  1077. // 77 | A4 Rotated (297 mm x 210 mm)
  1078. // 78 | A5 Rotated (210 mm x 148 mm)
  1079. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  1080. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  1081. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  1082. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  1083. // 83 | A6 Rotated (148 mm x 105 mm)
  1084. // 84 | Japanese Envelope Kaku #2 Rotated
  1085. // 85 | Japanese Envelope Kaku #3 Rotated
  1086. // 86 | Japanese Envelope Chou #3 Rotated
  1087. // 87 | Japanese Envelope Chou #4 Rotated
  1088. // 88 | B6 (JIS) (128 mm x 182 mm)
  1089. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  1090. // 90 | (12 in x 11 in)
  1091. // 91 | Japanese Envelope You #4
  1092. // 92 | Japanese Envelope You #4 Rotated
  1093. // 93 | PRC 16K (146 mm x 215 mm)
  1094. // 94 | PRC 32K (97 mm x 151 mm)
  1095. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  1096. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  1097. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  1098. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  1099. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  1100. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  1101. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  1102. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  1103. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  1104. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  1105. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  1106. // 106 | PRC 16K Rotated
  1107. // 107 | PRC 32K Rotated
  1108. // 108 | PRC 32K(Big) Rotated
  1109. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  1110. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  1111. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  1112. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  1113. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  1114. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  1115. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  1116. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  1117. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  1118. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  1119. //
  1120. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  1121. s, err := f.workSheetReader(sheet)
  1122. if err != nil {
  1123. return err
  1124. }
  1125. ps := s.PageSetUp
  1126. if ps == nil {
  1127. ps = new(xlsxPageSetUp)
  1128. s.PageSetUp = ps
  1129. }
  1130. for _, opt := range opts {
  1131. opt.setPageLayout(ps)
  1132. }
  1133. return err
  1134. }
  1135. // GetPageLayout provides a function to gets worksheet page layout.
  1136. //
  1137. // Available options:
  1138. // PageLayoutOrientation(string)
  1139. // PageLayoutPaperSize(int)
  1140. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  1141. s, err := f.workSheetReader(sheet)
  1142. if err != nil {
  1143. return err
  1144. }
  1145. ps := s.PageSetUp
  1146. for _, opt := range opts {
  1147. opt.getPageLayout(ps)
  1148. }
  1149. return err
  1150. }
  1151. // workSheetRelsReader provides a function to get the pointer to the structure
  1152. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1153. func (f *File) workSheetRelsReader(path string) *xlsxWorkbookRels {
  1154. if f.WorkSheetRels[path] == nil {
  1155. _, ok := f.XLSX[path]
  1156. if ok {
  1157. c := xlsxWorkbookRels{}
  1158. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &c)
  1159. f.WorkSheetRels[path] = &c
  1160. }
  1161. }
  1162. return f.WorkSheetRels[path]
  1163. }
  1164. // workSheetRelsWriter provides a function to save
  1165. // xl/worksheets/_rels/sheet%d.xml.rels after serialize structure.
  1166. func (f *File) workSheetRelsWriter() {
  1167. for p, r := range f.WorkSheetRels {
  1168. if r != nil {
  1169. v, _ := xml.Marshal(r)
  1170. f.saveFileList(p, v)
  1171. }
  1172. }
  1173. }
  1174. // fillSheetData ensures there are enough rows, and columns in the chosen
  1175. // row to accept data. Missing rows are backfilled and given their row number
  1176. func prepareSheetXML(xlsx *xlsxWorksheet, col int, row int) {
  1177. rowCount := len(xlsx.SheetData.Row)
  1178. if rowCount < row {
  1179. // append missing rows
  1180. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1181. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{R: rowIdx + 1})
  1182. }
  1183. }
  1184. rowData := &xlsx.SheetData.Row[row-1]
  1185. fillColumns(rowData, col, row)
  1186. }
  1187. func fillColumns(rowData *xlsxRow, col, row int) {
  1188. cellCount := len(rowData.C)
  1189. if cellCount < col {
  1190. for colIdx := cellCount; colIdx < col; colIdx++ {
  1191. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1192. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1193. }
  1194. }
  1195. }
  1196. func makeContiguousColumns(xlsx *xlsxWorksheet, fromRow, toRow, colCount int) {
  1197. for ; fromRow < toRow; fromRow++ {
  1198. rowData := &xlsx.SheetData.Row[fromRow-1]
  1199. fillColumns(rowData, colCount, fromRow)
  1200. }
  1201. }