sheet.go 49 KB

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