sheet.go 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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
  347. // of XLSX.
  348. func (f *File) getSheetMap() map[string]string {
  349. content := f.workbookReader()
  350. rels := f.workbookRelsReader()
  351. maps := map[string]string{}
  352. for _, v := range content.Sheets.Sheet {
  353. for _, rel := range rels.Relationships {
  354. if rel.ID == v.ID {
  355. maps[v.Name] = fmt.Sprintf("xl/%s", rel.Target)
  356. }
  357. }
  358. }
  359. return maps
  360. }
  361. // SetSheetBackground provides a function to set background picture by given
  362. // worksheet name and file path.
  363. func (f *File) SetSheetBackground(sheet, picture string) error {
  364. var err error
  365. // Check picture exists first.
  366. if _, err = os.Stat(picture); os.IsNotExist(err) {
  367. return err
  368. }
  369. ext, ok := supportImageTypes[path.Ext(picture)]
  370. if !ok {
  371. return errors.New("unsupported image extension")
  372. }
  373. file, _ := ioutil.ReadFile(picture)
  374. name := f.addMedia(file, ext)
  375. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, strings.Replace(name, "xl", "..", 1), "")
  376. f.addSheetPicture(sheet, rID)
  377. f.setContentTypePartImageExtensions()
  378. return err
  379. }
  380. // DeleteSheet provides a function to delete worksheet in a workbook by given
  381. // worksheet name. Use this method with caution, which will affect changes in
  382. // references such as formulas, charts, and so on. If there is any referenced
  383. // value of the deleted worksheet, it will cause a file error when you open it.
  384. // This function will be invalid when only the one worksheet is left.
  385. func (f *File) DeleteSheet(name string) {
  386. content := f.workbookReader()
  387. for k, v := range content.Sheets.Sheet {
  388. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  389. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  390. sheet := "xl/worksheets/sheet" + strconv.Itoa(v.SheetID) + ".xml"
  391. rels := "xl/worksheets/_rels/sheet" + strconv.Itoa(v.SheetID) + ".xml.rels"
  392. target := f.deleteSheetFromWorkbookRels(v.ID)
  393. f.deleteSheetFromContentTypes(target)
  394. f.deleteCalcChain(v.SheetID, "") // Delete CalcChain
  395. delete(f.sheetMap, name)
  396. delete(f.XLSX, sheet)
  397. delete(f.XLSX, rels)
  398. delete(f.Sheet, sheet)
  399. f.SheetCount--
  400. }
  401. }
  402. f.SetActiveSheet(len(f.GetSheetMap()))
  403. }
  404. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  405. // relationships by given relationships ID in the file
  406. // xl/_rels/workbook.xml.rels.
  407. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  408. content := f.workbookRelsReader()
  409. for k, v := range content.Relationships {
  410. if v.ID == rID {
  411. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  412. return v.Target
  413. }
  414. }
  415. return ""
  416. }
  417. // deleteSheetFromContentTypes provides a function to remove worksheet
  418. // relationships by given target name in the file [Content_Types].xml.
  419. func (f *File) deleteSheetFromContentTypes(target string) {
  420. content := f.contentTypesReader()
  421. for k, v := range content.Overrides {
  422. if v.PartName == "/xl/"+target {
  423. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  424. }
  425. }
  426. }
  427. // CopySheet provides a function to duplicate a worksheet by gave source and
  428. // target worksheet index. Note that currently doesn't support duplicate
  429. // workbooks that contain tables, charts or pictures. For Example:
  430. //
  431. // // Sheet1 already exists...
  432. // index := f.NewSheet("Sheet2")
  433. // err := f.CopySheet(1, index)
  434. // return err
  435. //
  436. func (f *File) CopySheet(from, to int) error {
  437. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  438. return errors.New("invalid worksheet index")
  439. }
  440. return f.copySheet(from, to)
  441. }
  442. // copySheet provides a function to duplicate a worksheet by gave source and
  443. // target worksheet name.
  444. func (f *File) copySheet(from, to int) error {
  445. sheet, err := f.workSheetReader(f.GetSheetName(from))
  446. if err != nil {
  447. return err
  448. }
  449. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  450. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  451. if len(worksheet.SheetViews.SheetView) > 0 {
  452. worksheet.SheetViews.SheetView[0].TabSelected = false
  453. }
  454. worksheet.Drawing = nil
  455. worksheet.TableParts = nil
  456. worksheet.PageSetUp = nil
  457. f.Sheet[path] = worksheet
  458. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  459. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  460. _, ok := f.XLSX[fromRels]
  461. if ok {
  462. f.XLSX[toRels] = f.XLSX[fromRels]
  463. }
  464. return err
  465. }
  466. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  467. // name. A workbook must contain at least one visible worksheet. If the given
  468. // worksheet has been activated, this setting will be invalidated. Sheet state
  469. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  470. //
  471. // visible
  472. // hidden
  473. // veryHidden
  474. //
  475. // For example, hide Sheet1:
  476. //
  477. // err := f.SetSheetVisible("Sheet1", false)
  478. //
  479. func (f *File) SetSheetVisible(name string, visible bool) error {
  480. name = trimSheetName(name)
  481. content := f.workbookReader()
  482. if visible {
  483. for k, v := range content.Sheets.Sheet {
  484. if v.Name == name {
  485. content.Sheets.Sheet[k].State = ""
  486. }
  487. }
  488. return nil
  489. }
  490. count := 0
  491. for _, v := range content.Sheets.Sheet {
  492. if v.State != "hidden" {
  493. count++
  494. }
  495. }
  496. for k, v := range content.Sheets.Sheet {
  497. xlsx, err := f.workSheetReader(v.Name)
  498. if err != nil {
  499. return err
  500. }
  501. tabSelected := false
  502. if len(xlsx.SheetViews.SheetView) > 0 {
  503. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  504. }
  505. if v.Name == name && count > 1 && !tabSelected {
  506. content.Sheets.Sheet[k].State = "hidden"
  507. }
  508. }
  509. return nil
  510. }
  511. // parseFormatPanesSet provides a function to parse the panes settings.
  512. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  513. format := formatPanes{}
  514. err := json.Unmarshal([]byte(formatSet), &format)
  515. return &format, err
  516. }
  517. // SetPanes provides a function to create and remove freeze panes and split panes
  518. // by given worksheet name and panes format set.
  519. //
  520. // activePane defines the pane that is active. The possible values for this
  521. // attribute are defined in the following table:
  522. //
  523. // Enumeration Value | Description
  524. // --------------------------------+-------------------------------------------------------------
  525. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  526. // | splits are applied.
  527. // |
  528. // | This value is also used when only a horizontal split has
  529. // | been applied, dividing the pane into upper and lower
  530. // | regions. In that case, this value specifies the bottom
  531. // | pane.
  532. // |
  533. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  534. // | splits are applied.
  535. // |
  536. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  537. // | are applied.
  538. // |
  539. // | This value is also used when only a horizontal split has
  540. // | been applied, dividing the pane into upper and lower
  541. // | regions. In that case, this value specifies the top pane.
  542. // |
  543. // | This value is also used when only a vertical split has
  544. // | been applied, dividing the pane into right and left
  545. // | regions. In that case, this value specifies the left pane
  546. // |
  547. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  548. // | splits are applied.
  549. // |
  550. // | This value is also used when only a vertical split has
  551. // | been applied, dividing the pane into right and left
  552. // | regions. In that case, this value specifies the right
  553. // | pane.
  554. //
  555. // Pane state type is restricted to the values supported currently listed in the following table:
  556. //
  557. // Enumeration Value | Description
  558. // --------------------------------+-------------------------------------------------------------
  559. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  560. // | this state, when the panes are unfrozen again, a single
  561. // | pane results, with no split.
  562. // |
  563. // | In this state, the split bars are not adjustable.
  564. // |
  565. // split (Split) | Panes are split, but not frozen. In this state, the split
  566. // | bars are adjustable by the user.
  567. //
  568. // x_split (Horizontal Split Position): Horizontal position of the split, in
  569. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  570. // indicates the number of columns visible in the top pane.
  571. //
  572. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  573. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  574. // number of rows visible in the left pane. The possible values for this
  575. // attribute are defined by the W3C XML Schema double datatype.
  576. //
  577. // top_left_cell: Location of the top left visible cell in the bottom right pane
  578. // (when in Left-To-Right mode).
  579. //
  580. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  581. // set of ranges.
  582. //
  583. // An example of how to freeze column A in the Sheet1 and set the active cell on
  584. // Sheet1!K16:
  585. //
  586. // 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"}]}`)
  587. //
  588. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  589. // ranges on Sheet1!A11:XFD11:
  590. //
  591. // 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"}]}`)
  592. //
  593. // An example of how to create split panes in the Sheet1 and set the active cell
  594. // on Sheet1!J60:
  595. //
  596. // 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"}]}`)
  597. //
  598. // An example of how to unfreeze and remove all panes on Sheet1:
  599. //
  600. // f.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  601. //
  602. func (f *File) SetPanes(sheet, panes string) error {
  603. fs, _ := parseFormatPanesSet(panes)
  604. xlsx, err := f.workSheetReader(sheet)
  605. if err != nil {
  606. return err
  607. }
  608. p := &xlsxPane{
  609. ActivePane: fs.ActivePane,
  610. TopLeftCell: fs.TopLeftCell,
  611. XSplit: float64(fs.XSplit),
  612. YSplit: float64(fs.YSplit),
  613. }
  614. if fs.Freeze {
  615. p.State = "frozen"
  616. }
  617. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  618. if !(fs.Freeze) && !(fs.Split) {
  619. if len(xlsx.SheetViews.SheetView) > 0 {
  620. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  621. }
  622. }
  623. s := []*xlsxSelection{}
  624. for _, p := range fs.Panes {
  625. s = append(s, &xlsxSelection{
  626. ActiveCell: p.ActiveCell,
  627. Pane: p.Pane,
  628. SQRef: p.SQRef,
  629. })
  630. }
  631. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  632. return err
  633. }
  634. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  635. // name. For example, get visible state of Sheet1:
  636. //
  637. // f.GetSheetVisible("Sheet1")
  638. //
  639. func (f *File) GetSheetVisible(name string) bool {
  640. content := f.workbookReader()
  641. visible := false
  642. for k, v := range content.Sheets.Sheet {
  643. if v.Name == trimSheetName(name) {
  644. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  645. visible = true
  646. }
  647. }
  648. }
  649. return visible
  650. }
  651. // SearchSheet provides a function to get coordinates by given worksheet name,
  652. // cell value, and regular expression. The function doesn't support searching
  653. // on the calculated result, formatted numbers and conditional lookup
  654. // currently. If it is a merged cell, it will return the coordinates of the
  655. // upper left corner of the merged area.
  656. //
  657. // An example of search the coordinates of the value of "100" on Sheet1:
  658. //
  659. // result, err := f.SearchSheet("Sheet1", "100")
  660. //
  661. // An example of search the coordinates where the numerical value in the range
  662. // of "0-9" of Sheet1 is described:
  663. //
  664. // result, err := f.SearchSheet("Sheet1", "[0-9]", true)
  665. //
  666. func (f *File) SearchSheet(sheet, value string, reg ...bool) ([]string, error) {
  667. var (
  668. regSearch bool
  669. result []string
  670. )
  671. for _, r := range reg {
  672. regSearch = r
  673. }
  674. xlsx, err := f.workSheetReader(sheet)
  675. if err != nil {
  676. return result, err
  677. }
  678. name, ok := f.sheetMap[trimSheetName(sheet)]
  679. if !ok {
  680. return result, nil
  681. }
  682. if xlsx != nil {
  683. output, _ := xml.Marshal(f.Sheet[name])
  684. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  685. }
  686. return f.searchSheet(name, value, regSearch)
  687. }
  688. // searchSheet provides a function to get coordinates by given worksheet name,
  689. // cell value, and regular expression.
  690. func (f *File) searchSheet(name, value string, regSearch bool) ([]string, error) {
  691. var (
  692. inElement string
  693. result []string
  694. r xlsxRow
  695. )
  696. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  697. d := f.sharedStringsReader()
  698. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  699. for {
  700. token, _ := decoder.Token()
  701. if token == nil {
  702. break
  703. }
  704. switch startElement := token.(type) {
  705. case xml.StartElement:
  706. inElement = startElement.Name.Local
  707. if inElement == "row" {
  708. r = xlsxRow{}
  709. _ = decoder.DecodeElement(&r, &startElement)
  710. for _, colCell := range r.C {
  711. val, _ := colCell.getValueFrom(f, d)
  712. if regSearch {
  713. regex := regexp.MustCompile(value)
  714. if !regex.MatchString(val) {
  715. continue
  716. }
  717. } else {
  718. if val != value {
  719. continue
  720. }
  721. }
  722. cellCol, _, err := CellNameToCoordinates(colCell.R)
  723. if err != nil {
  724. return result, err
  725. }
  726. cellName, err := CoordinatesToCellName(cellCol, r.R)
  727. if err != nil {
  728. return result, err
  729. }
  730. result = append(result, cellName)
  731. }
  732. }
  733. default:
  734. }
  735. }
  736. return result, nil
  737. }
  738. // SetHeaderFooter provides a function to set headers and footers by given
  739. // worksheet name and the control characters.
  740. //
  741. // Headers and footers are specified using the following settings fields:
  742. //
  743. // Fields | Description
  744. // ------------------+-----------------------------------------------------------
  745. // AlignWithMargins | Align header footer margins with page margins
  746. // DifferentFirst | Different first-page header and footer indicator
  747. // DifferentOddEven | Different odd and even page headers and footers indicator
  748. // ScaleWithDoc | Scale header and footer with document scaling
  749. // OddFooter | Odd Page Footer
  750. // OddHeader | Odd Header
  751. // EvenFooter | Even Page Footer
  752. // EvenHeader | Even Page Header
  753. // FirstFooter | First Page Footer
  754. // FirstHeader | First Page Header
  755. //
  756. // The following formatting codes can be used in 6 string type fields:
  757. // OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
  758. //
  759. // Formatting Code | Description
  760. // ------------------------+-------------------------------------------------------------------------
  761. // && | The character "&"
  762. // |
  763. // &font-size | Size of the text font, where font-size is a decimal font size in points
  764. // |
  765. // &"font name,font type" | A text font-name string, font name, and a text font-type string,
  766. // | font type
  767. // |
  768. // &"-,Regular" | Regular text format. Toggles bold and italic modes to off
  769. // |
  770. // &A | Current worksheet's tab name
  771. // |
  772. // &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off
  773. // |
  774. // &D | Current date
  775. // |
  776. // &C | Center section
  777. // |
  778. // &E | Double-underline text format
  779. // |
  780. // &F | Current workbook's file name
  781. // |
  782. // &G | Drawing object as background
  783. // |
  784. // &H | Shadow text format
  785. // |
  786. // &I or &"-,Italic" | Italic text format
  787. // |
  788. // &K | Text font color
  789. // |
  790. // | An RGB Color is specified as RRGGBB
  791. // |
  792. // | A Theme Color is specified as TTSNNN where TT is the theme color Id,
  793. // | S is either "+" or "-" of the tint/shade value, and NNN is the
  794. // | tint/shade value
  795. // |
  796. // &L | Left section
  797. // |
  798. // &N | Total number of pages
  799. // |
  800. // &O | Outline text format
  801. // |
  802. // &P[[+|-]n] | Without the optional suffix, the current page number in decimal
  803. // |
  804. // &R | Right section
  805. // |
  806. // &S | Strikethrough text format
  807. // |
  808. // &T | Current time
  809. // |
  810. // &U | Single-underline text format. If double-underline mode is on, the next
  811. // | occurrence in a section specifier toggles double-underline mode to off;
  812. // | otherwise, it toggles single-underline mode, from off to on, or vice
  813. // | versa. The default mode is off
  814. // |
  815. // &X | Superscript text format
  816. // |
  817. // &Y | Subscript text format
  818. // |
  819. // &Z | Current workbook's file path
  820. //
  821. // For example:
  822. //
  823. // err := f.SetHeaderFooter("Sheet1", &excelize.FormatHeaderFooter{
  824. // DifferentFirst: true,
  825. // DifferentOddEven: true,
  826. // OddHeader: "&R&P",
  827. // OddFooter: "&C&F",
  828. // EvenHeader: "&L&P",
  829. // EvenFooter: "&L&D&R&T",
  830. // FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  831. // })
  832. //
  833. // This example shows:
  834. //
  835. // - The first page has its own header and footer
  836. //
  837. // - Odd and even-numbered pages have different headers and footers
  838. //
  839. // - Current page number in the right section of odd-page headers
  840. //
  841. // - Current workbook's file name in the center section of odd-page footers
  842. //
  843. // - Current page number in the left section of even-page headers
  844. //
  845. // - Current date in the left section and the current time in the right section
  846. // of even-page footers
  847. //
  848. // - The text "Center Bold Header" on the first line of the center section of
  849. // the first page, and the date on the second line of the center section of
  850. // that same page
  851. //
  852. // - No footer on the first page
  853. //
  854. func (f *File) SetHeaderFooter(sheet string, settings *FormatHeaderFooter) error {
  855. xlsx, err := f.workSheetReader(sheet)
  856. if err != nil {
  857. return err
  858. }
  859. if settings == nil {
  860. xlsx.HeaderFooter = nil
  861. return err
  862. }
  863. v := reflect.ValueOf(*settings)
  864. // Check 6 string type fields: OddHeader, OddFooter, EvenHeader, EvenFooter,
  865. // FirstFooter, FirstHeader
  866. for i := 4; i < v.NumField()-1; i++ {
  867. if v.Field(i).Len() >= 255 {
  868. return fmt.Errorf("field %s must be less than 255 characters", v.Type().Field(i).Name)
  869. }
  870. }
  871. xlsx.HeaderFooter = &xlsxHeaderFooter{
  872. AlignWithMargins: settings.AlignWithMargins,
  873. DifferentFirst: settings.DifferentFirst,
  874. DifferentOddEven: settings.DifferentOddEven,
  875. ScaleWithDoc: settings.ScaleWithDoc,
  876. OddHeader: settings.OddHeader,
  877. OddFooter: settings.OddFooter,
  878. EvenHeader: settings.EvenHeader,
  879. EvenFooter: settings.EvenFooter,
  880. FirstFooter: settings.FirstFooter,
  881. FirstHeader: settings.FirstHeader,
  882. }
  883. return err
  884. }
  885. // ProtectSheet provides a function to prevent other users from accidentally
  886. // or deliberately changing, moving, or deleting data in a worksheet. For
  887. // example, protect Sheet1 with protection settings:
  888. //
  889. // err := f.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  890. // Password: "password",
  891. // EditScenarios: false,
  892. // })
  893. //
  894. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) error {
  895. xlsx, err := f.workSheetReader(sheet)
  896. if err != nil {
  897. return err
  898. }
  899. if settings == nil {
  900. settings = &FormatSheetProtection{
  901. EditObjects: true,
  902. EditScenarios: true,
  903. SelectLockedCells: true,
  904. }
  905. }
  906. xlsx.SheetProtection = &xlsxSheetProtection{
  907. AutoFilter: settings.AutoFilter,
  908. DeleteColumns: settings.DeleteColumns,
  909. DeleteRows: settings.DeleteRows,
  910. FormatCells: settings.FormatCells,
  911. FormatColumns: settings.FormatColumns,
  912. FormatRows: settings.FormatRows,
  913. InsertColumns: settings.InsertColumns,
  914. InsertHyperlinks: settings.InsertHyperlinks,
  915. InsertRows: settings.InsertRows,
  916. Objects: settings.EditObjects,
  917. PivotTables: settings.PivotTables,
  918. Scenarios: settings.EditScenarios,
  919. SelectLockedCells: settings.SelectLockedCells,
  920. SelectUnlockedCells: settings.SelectUnlockedCells,
  921. Sheet: true,
  922. Sort: settings.Sort,
  923. }
  924. if settings.Password != "" {
  925. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  926. }
  927. return err
  928. }
  929. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  930. func (f *File) UnprotectSheet(sheet string) error {
  931. xlsx, err := f.workSheetReader(sheet)
  932. if err != nil {
  933. return err
  934. }
  935. xlsx.SheetProtection = nil
  936. return err
  937. }
  938. // trimSheetName provides a function to trim invaild characters by given worksheet
  939. // name.
  940. func trimSheetName(name string) string {
  941. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  942. r := make([]rune, 0, 31)
  943. for _, v := range name {
  944. switch v {
  945. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  946. continue
  947. default:
  948. r = append(r, v)
  949. }
  950. if len(r) == 31 {
  951. break
  952. }
  953. }
  954. name = string(r)
  955. }
  956. return name
  957. }
  958. // PageLayoutOption is an option of a page layout of a worksheet. See
  959. // SetPageLayout().
  960. type PageLayoutOption interface {
  961. setPageLayout(layout *xlsxPageSetUp)
  962. }
  963. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  964. type PageLayoutOptionPtr interface {
  965. PageLayoutOption
  966. getPageLayout(layout *xlsxPageSetUp)
  967. }
  968. type (
  969. // PageLayoutOrientation defines the orientation of page layout for a
  970. // worksheet.
  971. PageLayoutOrientation string
  972. // PageLayoutPaperSize defines the paper size of the worksheet
  973. PageLayoutPaperSize int
  974. )
  975. const (
  976. // OrientationPortrait indicates page layout orientation id portrait.
  977. OrientationPortrait = "portrait"
  978. // OrientationLandscape indicates page layout orientation id landscape.
  979. OrientationLandscape = "landscape"
  980. )
  981. // setPageLayout provides a method to set the orientation for the worksheet.
  982. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  983. ps.Orientation = string(o)
  984. }
  985. // getPageLayout provides a method to get the orientation for the worksheet.
  986. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  987. // Excel default: portrait
  988. if ps == nil || ps.Orientation == "" {
  989. *o = OrientationPortrait
  990. return
  991. }
  992. *o = PageLayoutOrientation(ps.Orientation)
  993. }
  994. // setPageLayout provides a method to set the paper size for the worksheet.
  995. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  996. ps.PaperSize = int(p)
  997. }
  998. // getPageLayout provides a method to get the paper size for the worksheet.
  999. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  1000. // Excel default: 1
  1001. if ps == nil || ps.PaperSize == 0 {
  1002. *p = 1
  1003. return
  1004. }
  1005. *p = PageLayoutPaperSize(ps.PaperSize)
  1006. }
  1007. // SetPageLayout provides a function to sets worksheet page layout.
  1008. //
  1009. // Available options:
  1010. // PageLayoutOrientation(string)
  1011. // PageLayoutPaperSize(int)
  1012. //
  1013. // The following shows the paper size sorted by excelize index number:
  1014. //
  1015. // Index | Paper Size
  1016. // -------+-----------------------------------------------
  1017. // 1 | Letter paper (8.5 in. by 11 in.)
  1018. // 2 | Letter small paper (8.5 in. by 11 in.)
  1019. // 3 | Tabloid paper (11 in. by 17 in.)
  1020. // 4 | Ledger paper (17 in. by 11 in.)
  1021. // 5 | Legal paper (8.5 in. by 14 in.)
  1022. // 6 | Statement paper (5.5 in. by 8.5 in.)
  1023. // 7 | Executive paper (7.25 in. by 10.5 in.)
  1024. // 8 | A3 paper (297 mm by 420 mm)
  1025. // 9 | A4 paper (210 mm by 297 mm)
  1026. // 10 | A4 small paper (210 mm by 297 mm)
  1027. // 11 | A5 paper (148 mm by 210 mm)
  1028. // 12 | B4 paper (250 mm by 353 mm)
  1029. // 13 | B5 paper (176 mm by 250 mm)
  1030. // 14 | Folio paper (8.5 in. by 13 in.)
  1031. // 15 | Quarto paper (215 mm by 275 mm)
  1032. // 16 | Standard paper (10 in. by 14 in.)
  1033. // 17 | Standard paper (11 in. by 17 in.)
  1034. // 18 | Note paper (8.5 in. by 11 in.)
  1035. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  1036. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  1037. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  1038. // 22 | #12 envelope (4.75 in. by 11 in.)
  1039. // 23 | #14 envelope (5 in. by 11.5 in.)
  1040. // 24 | C paper (17 in. by 22 in.)
  1041. // 25 | D paper (22 in. by 34 in.)
  1042. // 26 | E paper (34 in. by 44 in.)
  1043. // 27 | DL envelope (110 mm by 220 mm)
  1044. // 28 | C5 envelope (162 mm by 229 mm)
  1045. // 29 | C3 envelope (324 mm by 458 mm)
  1046. // 30 | C4 envelope (229 mm by 324 mm)
  1047. // 31 | C6 envelope (114 mm by 162 mm)
  1048. // 32 | C65 envelope (114 mm by 229 mm)
  1049. // 33 | B4 envelope (250 mm by 353 mm)
  1050. // 34 | B5 envelope (176 mm by 250 mm)
  1051. // 35 | B6 envelope (176 mm by 125 mm)
  1052. // 36 | Italy envelope (110 mm by 230 mm)
  1053. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  1054. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  1055. // 39 | US standard fanfold (14.875 in. by 11 in.)
  1056. // 40 | German standard fanfold (8.5 in. by 12 in.)
  1057. // 41 | German legal fanfold (8.5 in. by 13 in.)
  1058. // 42 | ISO B4 (250 mm by 353 mm)
  1059. // 43 | Japanese postcard (100 mm by 148 mm)
  1060. // 44 | Standard paper (9 in. by 11 in.)
  1061. // 45 | Standard paper (10 in. by 11 in.)
  1062. // 46 | Standard paper (15 in. by 11 in.)
  1063. // 47 | Invite envelope (220 mm by 220 mm)
  1064. // 50 | Letter extra paper (9.275 in. by 12 in.)
  1065. // 51 | Legal extra paper (9.275 in. by 15 in.)
  1066. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  1067. // 53 | A4 extra paper (236 mm by 322 mm)
  1068. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  1069. // 55 | A4 transverse paper (210 mm by 297 mm)
  1070. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  1071. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  1072. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  1073. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  1074. // 60 | A4 plus paper (210 mm by 330 mm)
  1075. // 61 | A5 transverse paper (148 mm by 210 mm)
  1076. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  1077. // 63 | A3 extra paper (322 mm by 445 mm)
  1078. // 64 | A5 extra paper (174 mm by 235 mm)
  1079. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  1080. // 66 | A2 paper (420 mm by 594 mm)
  1081. // 67 | A3 transverse paper (297 mm by 420 mm)
  1082. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  1083. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  1084. // 70 | A6 (105 mm x 148 mm)
  1085. // 71 | Japanese Envelope Kaku #2
  1086. // 72 | Japanese Envelope Kaku #3
  1087. // 73 | Japanese Envelope Chou #3
  1088. // 74 | Japanese Envelope Chou #4
  1089. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  1090. // 76 | A3 Rotated (420 mm x 297 mm)
  1091. // 77 | A4 Rotated (297 mm x 210 mm)
  1092. // 78 | A5 Rotated (210 mm x 148 mm)
  1093. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  1094. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  1095. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  1096. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  1097. // 83 | A6 Rotated (148 mm x 105 mm)
  1098. // 84 | Japanese Envelope Kaku #2 Rotated
  1099. // 85 | Japanese Envelope Kaku #3 Rotated
  1100. // 86 | Japanese Envelope Chou #3 Rotated
  1101. // 87 | Japanese Envelope Chou #4 Rotated
  1102. // 88 | B6 (JIS) (128 mm x 182 mm)
  1103. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  1104. // 90 | (12 in x 11 in)
  1105. // 91 | Japanese Envelope You #4
  1106. // 92 | Japanese Envelope You #4 Rotated
  1107. // 93 | PRC 16K (146 mm x 215 mm)
  1108. // 94 | PRC 32K (97 mm x 151 mm)
  1109. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  1110. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  1111. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  1112. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  1113. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  1114. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  1115. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  1116. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  1117. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  1118. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  1119. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  1120. // 106 | PRC 16K Rotated
  1121. // 107 | PRC 32K Rotated
  1122. // 108 | PRC 32K(Big) Rotated
  1123. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  1124. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  1125. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  1126. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  1127. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  1128. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  1129. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  1130. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  1131. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  1132. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  1133. //
  1134. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  1135. s, err := f.workSheetReader(sheet)
  1136. if err != nil {
  1137. return err
  1138. }
  1139. ps := s.PageSetUp
  1140. if ps == nil {
  1141. ps = new(xlsxPageSetUp)
  1142. s.PageSetUp = ps
  1143. }
  1144. for _, opt := range opts {
  1145. opt.setPageLayout(ps)
  1146. }
  1147. return err
  1148. }
  1149. // GetPageLayout provides a function to gets worksheet page layout.
  1150. //
  1151. // Available options:
  1152. // PageLayoutOrientation(string)
  1153. // PageLayoutPaperSize(int)
  1154. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  1155. s, err := f.workSheetReader(sheet)
  1156. if err != nil {
  1157. return err
  1158. }
  1159. ps := s.PageSetUp
  1160. for _, opt := range opts {
  1161. opt.getPageLayout(ps)
  1162. }
  1163. return err
  1164. }
  1165. // SetDefinedName provides a function to set the defined names of the workbook
  1166. // or worksheet. If not specified scopr, the default scope is workbook.
  1167. // For example:
  1168. //
  1169. // f.SetDefinedName(&excelize.DefinedName{
  1170. // Name: "Amount",
  1171. // RefersTo: "Sheet1!$A$2:$D$5",
  1172. // Comment: "defined name comment",
  1173. // Scope: "Sheet2",
  1174. // })
  1175. //
  1176. func (f *File) SetDefinedName(definedName *DefinedName) error {
  1177. wb := f.workbookReader()
  1178. d := xlsxDefinedName{
  1179. Name: definedName.Name,
  1180. Comment: definedName.Comment,
  1181. Data: definedName.RefersTo,
  1182. }
  1183. if definedName.Scope != "" {
  1184. if sheetID := f.GetSheetIndex(definedName.Scope); sheetID != 0 {
  1185. sheetID--
  1186. d.LocalSheetID = &sheetID
  1187. }
  1188. }
  1189. if wb.DefinedNames != nil {
  1190. for _, dn := range wb.DefinedNames.DefinedName {
  1191. var scope string
  1192. if dn.LocalSheetID != nil {
  1193. scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1194. }
  1195. if scope == definedName.Scope && dn.Name == definedName.Name {
  1196. return errors.New("the same name already exists on scope")
  1197. }
  1198. }
  1199. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d)
  1200. return nil
  1201. }
  1202. wb.DefinedNames = &xlsxDefinedNames{
  1203. DefinedName: []xlsxDefinedName{d},
  1204. }
  1205. return nil
  1206. }
  1207. // GetDefinedName provides a function to get the defined names of the workbook
  1208. // or worksheet.
  1209. func (f *File) GetDefinedName() []DefinedName {
  1210. var definedNames []DefinedName
  1211. wb := f.workbookReader()
  1212. if wb.DefinedNames != nil {
  1213. for _, dn := range wb.DefinedNames.DefinedName {
  1214. definedName := DefinedName{
  1215. Name: dn.Name,
  1216. Comment: dn.Comment,
  1217. RefersTo: dn.Data,
  1218. Scope: "Workbook",
  1219. }
  1220. if dn.LocalSheetID != nil {
  1221. definedName.Scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1222. }
  1223. definedNames = append(definedNames, definedName)
  1224. }
  1225. }
  1226. return definedNames
  1227. }
  1228. // workSheetRelsReader provides a function to get the pointer to the structure
  1229. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1230. func (f *File) workSheetRelsReader(path string) *xlsxWorkbookRels {
  1231. if f.WorkSheetRels[path] == nil {
  1232. _, ok := f.XLSX[path]
  1233. if ok {
  1234. c := xlsxWorkbookRels{}
  1235. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &c)
  1236. f.WorkSheetRels[path] = &c
  1237. }
  1238. }
  1239. return f.WorkSheetRels[path]
  1240. }
  1241. // workSheetRelsWriter provides a function to save
  1242. // xl/worksheets/_rels/sheet%d.xml.rels after serialize structure.
  1243. func (f *File) workSheetRelsWriter() {
  1244. for p, r := range f.WorkSheetRels {
  1245. if r != nil {
  1246. v, _ := xml.Marshal(r)
  1247. f.saveFileList(p, v)
  1248. }
  1249. }
  1250. }
  1251. // fillSheetData ensures there are enough rows, and columns in the chosen
  1252. // row to accept data. Missing rows are backfilled and given their row number
  1253. func prepareSheetXML(xlsx *xlsxWorksheet, col int, row int) {
  1254. rowCount := len(xlsx.SheetData.Row)
  1255. if rowCount < row {
  1256. // append missing rows
  1257. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1258. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{R: rowIdx + 1})
  1259. }
  1260. }
  1261. rowData := &xlsx.SheetData.Row[row-1]
  1262. fillColumns(rowData, col, row)
  1263. }
  1264. func fillColumns(rowData *xlsxRow, col, row int) {
  1265. cellCount := len(rowData.C)
  1266. if cellCount < col {
  1267. for colIdx := cellCount; colIdx < col; colIdx++ {
  1268. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1269. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1270. }
  1271. }
  1272. }
  1273. func makeContiguousColumns(xlsx *xlsxWorksheet, fromRow, toRow, colCount int) {
  1274. for ; fromRow < toRow; fromRow++ {
  1275. rowData := &xlsx.SheetData.Row[fromRow-1]
  1276. fillColumns(rowData, colCount, fromRow)
  1277. }
  1278. }