sheet.go 36 KB

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