sheet.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. // Package excelize providing a set of functions that allow you to write to
  2. // and read from XLSX files. Support reads and writes XLSX file generated by
  3. // Microsoft Excel™ 2007 and later. Support save file without losing original
  4. // charts of XLSX. This library needs Go version 1.8 or later.
  5. //
  6. // Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
  7. // this source code is governed by a BSD-style license that can be found in
  8. // the LICENSE file.
  9. package excelize
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "encoding/xml"
  14. "errors"
  15. "os"
  16. "path"
  17. "strconv"
  18. "strings"
  19. "unicode/utf8"
  20. "github.com/mohae/deepcopy"
  21. )
  22. // NewSheet provides a function to create a new sheet by given worksheet name,
  23. // when creating a new XLSX file, the default sheet will be create, when you
  24. // create a new file.
  25. func (f *File) NewSheet(name string) int {
  26. // Check if the worksheet already exists
  27. if f.GetSheetIndex(name) != 0 {
  28. return f.SheetCount
  29. }
  30. f.SheetCount++
  31. // Update docProps/app.xml
  32. f.setAppXML()
  33. // Update [Content_Types].xml
  34. f.setContentTypes(f.SheetCount)
  35. // Create new sheet /xl/worksheets/sheet%d.xml
  36. f.setSheet(f.SheetCount, name)
  37. // Update xl/_rels/workbook.xml.rels
  38. rID := f.addXlsxWorkbookRels(f.SheetCount)
  39. // Update xl/workbook.xml
  40. f.setWorkbook(name, rID)
  41. return f.SheetCount
  42. }
  43. // contentTypesReader provides a function to get the pointer to the
  44. // [Content_Types].xml structure after deserialization.
  45. func (f *File) contentTypesReader() *xlsxTypes {
  46. if f.ContentTypes == nil {
  47. var content xlsxTypes
  48. _ = xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  49. f.ContentTypes = &content
  50. }
  51. return f.ContentTypes
  52. }
  53. // contentTypesWriter provides a function to save [Content_Types].xml after
  54. // serialize structure.
  55. func (f *File) contentTypesWriter() {
  56. if f.ContentTypes != nil {
  57. output, _ := xml.Marshal(f.ContentTypes)
  58. f.saveFileList("[Content_Types].xml", output)
  59. }
  60. }
  61. // workbookReader provides a function to get the pointer to the xl/workbook.xml
  62. // structure after deserialization.
  63. func (f *File) workbookReader() *xlsxWorkbook {
  64. if f.WorkBook == nil {
  65. var content xlsxWorkbook
  66. _ = xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  67. f.WorkBook = &content
  68. }
  69. return f.WorkBook
  70. }
  71. // workbookWriter provides a function to save xl/workbook.xml after serialize
  72. // structure.
  73. func (f *File) workbookWriter() {
  74. if f.WorkBook != nil {
  75. output, _ := xml.Marshal(f.WorkBook)
  76. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpaceBytes(output))
  77. }
  78. }
  79. // worksheetWriter provides a function to save xl/worksheets/sheet%d.xml after
  80. // serialize structure.
  81. func (f *File) worksheetWriter() {
  82. for path, sheet := range f.Sheet {
  83. if sheet != nil {
  84. for k, v := range sheet.SheetData.Row {
  85. f.Sheet[path].SheetData.Row[k].C = trimCell(v.C)
  86. }
  87. output, _ := xml.Marshal(sheet)
  88. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  89. ok := f.checked[path]
  90. if ok {
  91. f.checked[path] = false
  92. }
  93. }
  94. }
  95. }
  96. // trimCell provides a function to trim blank cells which created by completeCol.
  97. func trimCell(column []xlsxC) []xlsxC {
  98. col := make([]xlsxC, len(column))
  99. i := 0
  100. for _, c := range column {
  101. if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
  102. col[i] = c
  103. i++
  104. }
  105. }
  106. return col[0:i]
  107. }
  108. // Read and update property of contents type of XLSX.
  109. func (f *File) setContentTypes(index int) {
  110. content := f.contentTypesReader()
  111. content.Overrides = append(content.Overrides, xlsxOverride{
  112. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  113. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  114. })
  115. }
  116. // Update sheet property by given index.
  117. func (f *File) setSheet(index int, name string) {
  118. var xlsx xlsxWorksheet
  119. xlsx.Dimension.Ref = "A1"
  120. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  121. WorkbookViewID: 0,
  122. })
  123. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  124. f.sheetMap[trimSheetName(name)] = path
  125. f.Sheet[path] = &xlsx
  126. }
  127. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  128. // allowed in sheet title.
  129. func (f *File) setWorkbook(name string, rid int) {
  130. content := f.workbookReader()
  131. rID := 0
  132. for _, v := range content.Sheets.Sheet {
  133. t, _ := strconv.Atoi(v.SheetID)
  134. if t > rID {
  135. rID = t
  136. }
  137. }
  138. rID++
  139. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  140. Name: trimSheetName(name),
  141. SheetID: strconv.Itoa(rID),
  142. ID: "rId" + strconv.Itoa(rid),
  143. })
  144. }
  145. // workbookRelsReader provides a function to read and unmarshal workbook
  146. // relationships of XLSX file.
  147. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  148. if f.WorkBookRels == nil {
  149. var content xlsxWorkbookRels
  150. _ = xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  151. f.WorkBookRels = &content
  152. }
  153. return f.WorkBookRels
  154. }
  155. // workbookRelsWriter provides a function to save xl/_rels/workbook.xml.rels after
  156. // serialize structure.
  157. func (f *File) workbookRelsWriter() {
  158. if f.WorkBookRels != nil {
  159. output, _ := xml.Marshal(f.WorkBookRels)
  160. f.saveFileList("xl/_rels/workbook.xml.rels", output)
  161. }
  162. }
  163. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  164. func (f *File) addXlsxWorkbookRels(sheet int) int {
  165. content := f.workbookRelsReader()
  166. rID := 0
  167. for _, v := range content.Relationships {
  168. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  169. if t > rID {
  170. rID = t
  171. }
  172. }
  173. rID++
  174. ID := bytes.Buffer{}
  175. ID.WriteString("rId")
  176. ID.WriteString(strconv.Itoa(rID))
  177. target := bytes.Buffer{}
  178. target.WriteString("worksheets/sheet")
  179. target.WriteString(strconv.Itoa(sheet))
  180. target.WriteString(".xml")
  181. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  182. ID: ID.String(),
  183. Target: target.String(),
  184. Type: SourceRelationshipWorkSheet,
  185. })
  186. return rID
  187. }
  188. // setAppXML update docProps/app.xml file of XML.
  189. func (f *File) setAppXML() {
  190. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  191. }
  192. // Some tools that read XLSX files have very strict requirements about the
  193. // structure of the input XML. In particular both Numbers on the Mac and SAS
  194. // dislike inline XML namespace declarations, or namespace prefixes that don't
  195. // match the ones that Excel itself uses. This is a problem because the Go XML
  196. // library doesn't multiple namespace declarations in a single element of a
  197. // document. This function is a horrible hack to fix that after the XML
  198. // marshalling is completed.
  199. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  200. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  201. 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">`)
  202. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  203. }
  204. // SetActiveSheet provides a function to set default active worksheet of XLSX by
  205. // given index. Note that active index is different with the index that got by
  206. // function GetSheetMap, and it should be greater than 0 and less than total
  207. // worksheet numbers.
  208. func (f *File) SetActiveSheet(index int) {
  209. if index < 1 {
  210. index = 1
  211. }
  212. index--
  213. content := f.workbookReader()
  214. if len(content.BookViews.WorkBookView) > 0 {
  215. content.BookViews.WorkBookView[0].ActiveTab = index
  216. } else {
  217. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  218. ActiveTab: index,
  219. })
  220. }
  221. index++
  222. for idx, name := range f.GetSheetMap() {
  223. xlsx := f.workSheetReader(name)
  224. if index == idx {
  225. if len(xlsx.SheetViews.SheetView) > 0 {
  226. xlsx.SheetViews.SheetView[0].TabSelected = true
  227. } else {
  228. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  229. TabSelected: true,
  230. })
  231. }
  232. } else {
  233. if len(xlsx.SheetViews.SheetView) > 0 {
  234. xlsx.SheetViews.SheetView[0].TabSelected = false
  235. }
  236. }
  237. }
  238. }
  239. // GetActiveSheetIndex provides a function to get active sheet of XLSX. If not
  240. // found the active sheet will be return integer 0.
  241. func (f *File) GetActiveSheetIndex() int {
  242. buffer := bytes.Buffer{}
  243. content := f.workbookReader()
  244. for _, v := range content.Sheets.Sheet {
  245. xlsx := xlsxWorksheet{}
  246. buffer.WriteString("xl/worksheets/sheet")
  247. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  248. buffer.WriteString(".xml")
  249. _ = xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  250. for _, sheetView := range xlsx.SheetViews.SheetView {
  251. if sheetView.TabSelected {
  252. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  253. return ID
  254. }
  255. }
  256. buffer.Reset()
  257. }
  258. return 0
  259. }
  260. // SetSheetName provides a function to set the worksheet name be given old and new
  261. // worksheet name. Maximum 31 characters are allowed in sheet title and this
  262. // function only changes the name of the sheet and will not update the sheet
  263. // name in the formula or reference associated with the cell. So there may be
  264. // problem formula error or reference missing.
  265. func (f *File) SetSheetName(oldName, newName string) {
  266. oldName = trimSheetName(oldName)
  267. newName = trimSheetName(newName)
  268. content := f.workbookReader()
  269. for k, v := range content.Sheets.Sheet {
  270. if v.Name == oldName {
  271. content.Sheets.Sheet[k].Name = newName
  272. f.sheetMap[newName] = f.sheetMap[oldName]
  273. delete(f.sheetMap, oldName)
  274. }
  275. }
  276. }
  277. // GetSheetName provides a function to get worksheet name of XLSX by given
  278. // worksheet index. If given sheet index is invalid, will return an empty
  279. // string.
  280. func (f *File) GetSheetName(index int) string {
  281. content := f.workbookReader()
  282. rels := f.workbookRelsReader()
  283. for _, rel := range rels.Relationships {
  284. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  285. if rID == index {
  286. for _, v := range content.Sheets.Sheet {
  287. if v.ID == rel.ID {
  288. return v.Name
  289. }
  290. }
  291. }
  292. }
  293. return ""
  294. }
  295. // GetSheetIndex provides a function to get worksheet index of XLSX by given sheet
  296. // name. If given worksheet name is invalid, will return an integer type value
  297. // 0.
  298. func (f *File) GetSheetIndex(name string) int {
  299. content := f.workbookReader()
  300. rels := f.workbookRelsReader()
  301. for _, v := range content.Sheets.Sheet {
  302. if v.Name == name {
  303. for _, rel := range rels.Relationships {
  304. if v.ID == rel.ID {
  305. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  306. return rID
  307. }
  308. }
  309. }
  310. }
  311. return 0
  312. }
  313. // GetSheetMap provides a function to get worksheet name and index map of XLSX.
  314. // For example:
  315. //
  316. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  317. // if err != nil {
  318. // return
  319. // }
  320. // for index, name := range xlsx.GetSheetMap() {
  321. // fmt.Println(index, name)
  322. // }
  323. //
  324. func (f *File) GetSheetMap() map[int]string {
  325. content := f.workbookReader()
  326. rels := f.workbookRelsReader()
  327. sheetMap := map[int]string{}
  328. for _, v := range content.Sheets.Sheet {
  329. for _, rel := range rels.Relationships {
  330. if rel.ID == v.ID {
  331. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  332. sheetMap[rID] = v.Name
  333. }
  334. }
  335. }
  336. return sheetMap
  337. }
  338. // getSheetMap provides a function to get worksheet name and XML file path map of
  339. // XLSX.
  340. func (f *File) getSheetMap() map[string]string {
  341. maps := make(map[string]string)
  342. for idx, name := range f.GetSheetMap() {
  343. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  344. }
  345. return maps
  346. }
  347. // SetSheetBackground provides a function to set background picture by given
  348. // worksheet name.
  349. func (f *File) SetSheetBackground(sheet, picture string) error {
  350. var err error
  351. // Check picture exists first.
  352. if _, err = os.Stat(picture); os.IsNotExist(err) {
  353. return err
  354. }
  355. ext, ok := supportImageTypes[path.Ext(picture)]
  356. if !ok {
  357. return errors.New("unsupported image extension")
  358. }
  359. pictureID := f.countMedia() + 1
  360. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  361. f.addSheetPicture(sheet, rID)
  362. f.addMedia(picture, 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" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  377. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".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. // trimSheetName provides a function to trim invaild characters by given worksheet
  626. // name.
  627. func trimSheetName(name string) string {
  628. r := []rune{}
  629. for _, v := range name {
  630. switch v {
  631. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  632. continue
  633. default:
  634. r = append(r, v)
  635. }
  636. }
  637. name = string(r)
  638. if utf8.RuneCountInString(name) > 31 {
  639. name = string([]rune(name)[0:31])
  640. }
  641. return name
  642. }