sheet.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "errors"
  7. "os"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "unicode/utf8"
  12. )
  13. // NewSheet provides function to create a new sheet by given index, when
  14. // creating a new XLSX file, the default sheet will be create, when you create a
  15. // new file.
  16. func (f *File) NewSheet(name string) int {
  17. f.SheetCount++
  18. // Update docProps/app.xml
  19. f.setAppXML()
  20. // Update [Content_Types].xml
  21. f.setContentTypes(f.SheetCount)
  22. // Create new sheet /xl/worksheets/sheet%d.xml
  23. f.setSheet(f.SheetCount, name)
  24. // Update xl/_rels/workbook.xml.rels
  25. rID := f.addXlsxWorkbookRels(f.SheetCount)
  26. // Update xl/workbook.xml
  27. f.setWorkbook(name, rID)
  28. return f.SheetCount
  29. }
  30. // contentTypesReader provides function to get the pointer to the
  31. // [Content_Types].xml structure after deserialization.
  32. func (f *File) contentTypesReader() *xlsxTypes {
  33. if f.ContentTypes == nil {
  34. var content xlsxTypes
  35. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  36. f.ContentTypes = &content
  37. }
  38. return f.ContentTypes
  39. }
  40. // contentTypesWriter provides function to save [Content_Types].xml after
  41. // serialize structure.
  42. func (f *File) contentTypesWriter() {
  43. if f.ContentTypes != nil {
  44. output, _ := xml.Marshal(f.ContentTypes)
  45. f.saveFileList("[Content_Types].xml", string(output))
  46. }
  47. }
  48. // workbookReader provides function to get the pointer to the xl/workbook.xml
  49. // structure after deserialization.
  50. func (f *File) workbookReader() *xlsxWorkbook {
  51. if f.WorkBook == nil {
  52. var content xlsxWorkbook
  53. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  54. f.WorkBook = &content
  55. }
  56. return f.WorkBook
  57. }
  58. // workbookWriter provides function to save xl/workbook.xml after serialize
  59. // structure.
  60. func (f *File) workbookWriter() {
  61. if f.WorkBook != nil {
  62. output, _ := xml.Marshal(f.WorkBook)
  63. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  64. }
  65. }
  66. // worksheetWriter provides function to save xl/worksheets/sheet%d.xml after
  67. // serialize structure.
  68. func (f *File) worksheetWriter() {
  69. for path, sheet := range f.Sheet {
  70. if sheet != nil {
  71. for k, v := range sheet.SheetData.Row {
  72. f.Sheet[path].SheetData.Row[k].C = trimCell(v.C)
  73. }
  74. output, _ := xml.Marshal(sheet)
  75. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  76. ok := f.checked[path]
  77. if ok {
  78. f.checked[path] = false
  79. }
  80. }
  81. }
  82. }
  83. // trimCell provides function to trim blank cells which created by completeCol.
  84. func trimCell(column []xlsxC) []xlsxC {
  85. col := []xlsxC{}
  86. for _, c := range column {
  87. if c.S == 0 && c.V == "" && c.F == nil && c.T == "" {
  88. continue
  89. }
  90. col = append(col, c)
  91. }
  92. return col
  93. }
  94. // Read and update property of contents type of XLSX.
  95. func (f *File) setContentTypes(index int) {
  96. content := f.contentTypesReader()
  97. content.Overrides = append(content.Overrides, xlsxOverride{
  98. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  99. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  100. })
  101. }
  102. // Update sheet property by given index.
  103. func (f *File) setSheet(index int, name string) {
  104. var xlsx xlsxWorksheet
  105. xlsx.Dimension.Ref = "A1"
  106. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  107. WorkbookViewID: 0,
  108. })
  109. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  110. f.sheetMap[trimSheetName(name)] = path
  111. f.Sheet[path] = &xlsx
  112. }
  113. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  114. // allowed in sheet title.
  115. func (f *File) setWorkbook(name string, rid int) {
  116. content := f.workbookReader()
  117. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  118. Name: trimSheetName(name),
  119. SheetID: strconv.Itoa(rid),
  120. ID: "rId" + strconv.Itoa(rid),
  121. })
  122. }
  123. // workbookRelsReader provides function to read and unmarshal workbook
  124. // relationships of XLSX file.
  125. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  126. if f.WorkBookRels == nil {
  127. var content xlsxWorkbookRels
  128. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  129. f.WorkBookRels = &content
  130. }
  131. return f.WorkBookRels
  132. }
  133. // workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
  134. // serialize structure.
  135. func (f *File) workbookRelsWriter() {
  136. if f.WorkBookRels != nil {
  137. output, _ := xml.Marshal(f.WorkBookRels)
  138. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  139. }
  140. }
  141. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  142. func (f *File) addXlsxWorkbookRels(sheet int) int {
  143. content := f.workbookRelsReader()
  144. rID := 0
  145. for _, v := range content.Relationships {
  146. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  147. if t > rID {
  148. rID = t
  149. }
  150. }
  151. rID++
  152. ID := bytes.Buffer{}
  153. ID.WriteString("rId")
  154. ID.WriteString(strconv.Itoa(rID))
  155. target := bytes.Buffer{}
  156. target.WriteString("worksheets/sheet")
  157. target.WriteString(strconv.Itoa(sheet))
  158. target.WriteString(".xml")
  159. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  160. ID: ID.String(),
  161. Target: target.String(),
  162. Type: SourceRelationshipWorkSheet,
  163. })
  164. return rID
  165. }
  166. // setAppXML update docProps/app.xml file of XML.
  167. func (f *File) setAppXML() {
  168. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  169. }
  170. // Some tools that read XLSX files have very strict requirements about the
  171. // structure of the input XML. In particular both Numbers on the Mac and SAS
  172. // dislike inline XML namespace declarations, or namespace prefixes that don't
  173. // match the ones that Excel itself uses. This is a problem because the Go XML
  174. // library doesn't multiple namespace declarations in a single element of a
  175. // document. This function is a horrible hack to fix that after the XML
  176. // marshalling is completed.
  177. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  178. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  179. newXmlns := `<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">`
  180. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  181. }
  182. // SetActiveSheet provides function to set default active sheet of XLSX by given
  183. // index.
  184. func (f *File) SetActiveSheet(index int) {
  185. if index < 1 {
  186. index = 1
  187. }
  188. index--
  189. content := f.workbookReader()
  190. if len(content.BookViews.WorkBookView) > 0 {
  191. content.BookViews.WorkBookView[0].ActiveTab = index
  192. } else {
  193. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  194. ActiveTab: index,
  195. })
  196. }
  197. index++
  198. for idx, name := range f.GetSheetMap() {
  199. xlsx := f.workSheetReader(name)
  200. if index == idx {
  201. if len(xlsx.SheetViews.SheetView) > 0 {
  202. xlsx.SheetViews.SheetView[0].TabSelected = true
  203. } else {
  204. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  205. TabSelected: true,
  206. })
  207. }
  208. } else {
  209. if len(xlsx.SheetViews.SheetView) > 0 {
  210. xlsx.SheetViews.SheetView[0].TabSelected = false
  211. }
  212. }
  213. }
  214. return
  215. }
  216. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  217. // found the active sheet will be return integer 0.
  218. func (f *File) GetActiveSheetIndex() int {
  219. buffer := bytes.Buffer{}
  220. content := f.workbookReader()
  221. for _, v := range content.Sheets.Sheet {
  222. xlsx := xlsxWorksheet{}
  223. buffer.WriteString("xl/worksheets/sheet")
  224. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  225. buffer.WriteString(".xml")
  226. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  227. for _, sheetView := range xlsx.SheetViews.SheetView {
  228. if sheetView.TabSelected {
  229. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  230. return ID
  231. }
  232. }
  233. buffer.Reset()
  234. }
  235. return 0
  236. }
  237. // SetSheetName provides function to set the worksheet name be given old and new
  238. // worksheet name. Maximum 31 characters are allowed in sheet title and this
  239. // function only changes the name of the sheet and will not update the sheet
  240. // name in the formula or reference associated with the cell. So there may be
  241. // problem formula error or reference missing.
  242. func (f *File) SetSheetName(oldName, newName string) {
  243. oldName = trimSheetName(oldName)
  244. newName = trimSheetName(newName)
  245. content := f.workbookReader()
  246. for k, v := range content.Sheets.Sheet {
  247. if v.Name == oldName {
  248. content.Sheets.Sheet[k].Name = newName
  249. f.sheetMap[newName] = f.sheetMap[oldName]
  250. delete(f.sheetMap, oldName)
  251. }
  252. }
  253. }
  254. // GetSheetName provides function to get worksheet name of XLSX by given
  255. // worksheet index. If given sheet index is invalid, will return an empty
  256. // string.
  257. func (f *File) GetSheetName(index int) string {
  258. content := f.workbookReader()
  259. rels := f.workbookRelsReader()
  260. for _, rel := range rels.Relationships {
  261. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  262. if rID == index {
  263. for _, v := range content.Sheets.Sheet {
  264. if v.ID == rel.ID {
  265. return v.Name
  266. }
  267. }
  268. }
  269. }
  270. return ""
  271. }
  272. // GetSheetIndex provides function to get worksheet index of XLSX by given sheet
  273. // name. If given worksheet name is invalid, will return an integer type value
  274. // 0.
  275. func (f *File) GetSheetIndex(name string) int {
  276. content := f.workbookReader()
  277. rels := f.workbookRelsReader()
  278. for _, v := range content.Sheets.Sheet {
  279. if v.Name == name {
  280. for _, rel := range rels.Relationships {
  281. if v.ID == rel.ID {
  282. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  283. return rID
  284. }
  285. }
  286. }
  287. }
  288. return 0
  289. }
  290. // GetSheetMap provides function to get worksheet name and index map of XLSX.
  291. // For example:
  292. //
  293. // xlsx, err := excelize.OpenFile("./Workbook.xlsx")
  294. // if err != nil {
  295. // fmt.Println(err)
  296. // os.Exit(1)
  297. // }
  298. // for index, name := range xlsx.GetSheetMap() {
  299. // fmt.Println(index, name)
  300. // }
  301. //
  302. func (f *File) GetSheetMap() map[int]string {
  303. content := f.workbookReader()
  304. rels := f.workbookRelsReader()
  305. sheetMap := map[int]string{}
  306. for _, v := range content.Sheets.Sheet {
  307. for _, rel := range rels.Relationships {
  308. if rel.ID == v.ID {
  309. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  310. sheetMap[rID] = v.Name
  311. }
  312. }
  313. }
  314. return sheetMap
  315. }
  316. // getSheetMap provides function to get worksheet name and XML file path map of
  317. // XLSX.
  318. func (f *File) getSheetMap() map[string]string {
  319. maps := make(map[string]string)
  320. for idx, name := range f.GetSheetMap() {
  321. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  322. }
  323. return maps
  324. }
  325. // SetSheetBackground provides function to set background picture by given
  326. // worksheet name.
  327. func (f *File) SetSheetBackground(sheet, picture string) error {
  328. var err error
  329. // Check picture exists first.
  330. if _, err = os.Stat(picture); os.IsNotExist(err) {
  331. return err
  332. }
  333. ext, ok := supportImageTypes[path.Ext(picture)]
  334. if !ok {
  335. return errors.New("Unsupported image extension")
  336. }
  337. pictureID := f.countMedia() + 1
  338. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  339. f.addSheetPicture(sheet, rID)
  340. f.addMedia(picture, ext)
  341. f.setContentTypePartImageExtensions()
  342. return err
  343. }
  344. // DeleteSheet provides function to delete worksheet in a workbook by given
  345. // worksheet name. Use this method with caution, which will affect changes in
  346. // references such as formulas, charts, and so on. If there is any referenced
  347. // value of the deleted worksheet, it will cause a file error when you open it.
  348. // This function will be invalid when only the one worksheet is left.
  349. func (f *File) DeleteSheet(name string) {
  350. content := f.workbookReader()
  351. for k, v := range content.Sheets.Sheet {
  352. if v.Name != trimSheetName(name) || len(content.Sheets.Sheet) < 2 {
  353. continue
  354. }
  355. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  356. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  357. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  358. target := f.deleteSheetFromWorkbookRels(v.ID)
  359. f.deleteSheetFromContentTypes(target)
  360. delete(f.sheetMap, name)
  361. delete(f.XLSX, sheet)
  362. delete(f.XLSX, rels)
  363. delete(f.Sheet, sheet)
  364. f.SheetCount--
  365. }
  366. }
  367. // deleteSheetFromWorkbookRels provides function to remove worksheet
  368. // relationships by given relationships ID in the file
  369. // xl/_rels/workbook.xml.rels.
  370. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  371. content := f.workbookRelsReader()
  372. for k, v := range content.Relationships {
  373. if v.ID != rID {
  374. continue
  375. }
  376. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  377. return v.Target
  378. }
  379. return ""
  380. }
  381. // deleteSheetFromContentTypes provides function to remove worksheet
  382. // relationships by given target name in the file [Content_Types].xml.
  383. func (f *File) deleteSheetFromContentTypes(target string) {
  384. content := f.contentTypesReader()
  385. for k, v := range content.Overrides {
  386. if v.PartName != "/xl/"+target {
  387. continue
  388. }
  389. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  390. }
  391. }
  392. // CopySheet provides function to duplicate a worksheet by gave source and
  393. // target worksheet index. Note that currently doesn't support duplicate
  394. // workbooks that contain tables, charts or pictures. For Example:
  395. //
  396. // // Sheet1 already exists...
  397. // index := xlsx.NewSheet("Sheet2")
  398. // err := xlsx.CopySheet(1, index)
  399. // if err != nil {
  400. // fmt.Println(err)
  401. // os.Exit(1)
  402. // }
  403. //
  404. func (f *File) CopySheet(from, to int) error {
  405. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  406. return errors.New("Invalid worksheet index")
  407. }
  408. f.copySheet(from, to)
  409. return nil
  410. }
  411. // copySheet provides function to duplicate a worksheet by gave source and
  412. // target worksheet name.
  413. func (f *File) copySheet(from, to int) {
  414. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  415. worksheet := xlsxWorksheet{}
  416. deepCopy(&worksheet, &sheet)
  417. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  418. if len(worksheet.SheetViews.SheetView) > 0 {
  419. worksheet.SheetViews.SheetView[0].TabSelected = false
  420. }
  421. worksheet.Drawing = nil
  422. worksheet.TableParts = nil
  423. worksheet.PageSetUp = nil
  424. f.Sheet[path] = &worksheet
  425. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  426. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  427. _, ok := f.XLSX[fromRels]
  428. if ok {
  429. f.XLSX[toRels] = f.XLSX[fromRels]
  430. }
  431. }
  432. // SetSheetVisible provides function to set worksheet visible by given worksheet
  433. // name. A workbook must contain at least one visible worksheet. If the given
  434. // worksheet has been activated, this setting will be invalidated. Sheet state
  435. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  436. //
  437. // visible
  438. // hidden
  439. // veryHidden
  440. //
  441. // For example, hide Sheet1:
  442. //
  443. // xlsx.SetSheetVisible("Sheet1", false)
  444. //
  445. func (f *File) SetSheetVisible(name string, visible bool) {
  446. name = trimSheetName(name)
  447. content := f.workbookReader()
  448. if visible {
  449. for k, v := range content.Sheets.Sheet {
  450. if v.Name == name {
  451. content.Sheets.Sheet[k].State = ""
  452. }
  453. }
  454. return
  455. }
  456. count := 0
  457. for _, v := range content.Sheets.Sheet {
  458. if v.State != "hidden" {
  459. count++
  460. }
  461. }
  462. for k, v := range content.Sheets.Sheet {
  463. xlsx := f.workSheetReader(f.GetSheetMap()[k])
  464. tabSelected := false
  465. if len(xlsx.SheetViews.SheetView) > 0 {
  466. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  467. }
  468. if v.Name == name && count > 1 && !tabSelected {
  469. content.Sheets.Sheet[k].State = "hidden"
  470. }
  471. }
  472. }
  473. // parseFormatPanesSet provides function to parse the panes settings.
  474. func parseFormatPanesSet(formatSet string) *formatPanes {
  475. format := formatPanes{}
  476. json.Unmarshal([]byte(formatSet), &format)
  477. return &format
  478. }
  479. // SetPanes provides function to create and remove freeze panes and split panes
  480. // by given worksheet name and panes format set.
  481. //
  482. // activePane defines the pane that is active. The possible values for this
  483. // attribute are defined in the following table:
  484. //
  485. // Enumeration Value | Description
  486. // --------------------------------+-------------------------------------------------------------
  487. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  488. // | splits are applied.
  489. // |
  490. // | This value is also used when only a horizontal split has
  491. // | been applied, dividing the pane into upper and lower
  492. // | regions. In that case, this value specifies the bottom
  493. // | pane.
  494. // |
  495. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  496. // | splits are applied.
  497. // |
  498. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  499. // | are applied.
  500. // |
  501. // | This value is also used when only a horizontal split has
  502. // | been applied, dividing the pane into upper and lower
  503. // | regions. In that case, this value specifies the top pane.
  504. // |
  505. // | This value is also used when only a vertical split has
  506. // | been applied, dividing the pane into right and left
  507. // | regions. In that case, this value specifies the left pane
  508. // |
  509. // | Top right pane, when both vertical and horizontal
  510. // | splits are applied.
  511. // |
  512. // topRight (Top Right Pane) | This value is also used when only a vertical split has
  513. // | splits are applied.
  514. // |
  515. // |
  516. // | This value is also used when only a vertical split has
  517. // | been applied, dividing the pane into right and left
  518. // | regions. In that case, this value specifies the right
  519. // | pane.
  520. //
  521. // Pane state type is restricted to the values supported currently listed in the following table:
  522. //
  523. // Enumeration Value | Description
  524. // --------------------------------+-------------------------------------------------------------
  525. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  526. // | this state, when the panes are unfrozen again, a single
  527. // | pane results, with no split.
  528. // |
  529. // | In this state, the split bars are not adjustable.
  530. // |
  531. // split (Split) | Panes are split, but not frozen. In this state, the split
  532. // | bars are adjustable by the user.
  533. //
  534. // x_split (Horizontal Split Position): Horizontal position of the split, in
  535. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  536. // indicates the number of columns visible in the top pane.
  537. //
  538. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  539. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  540. // number of rows visible in the left pane. The possible values for this
  541. // attribute are defined by the W3C XML Schema double datatype.
  542. //
  543. // top_left_cell: Location of the top left visible cell in the bottom right pane
  544. // (when in Left-To-Right mode).
  545. //
  546. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  547. // set of ranges.
  548. //
  549. // An example of how to freeze column A in the Sheet1 and set the active cell on
  550. // Sheet1!A16:
  551. //
  552. // xlsx.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":1,"y_split":0,"topLeftCell":"B1","activePane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`)
  553. //
  554. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  555. // on Sheet1!A11:
  556. //
  557. // xlsx.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"topLeftCell":"A34","activePane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`)
  558. //
  559. // An example of how to create split panes in the Sheet1 and set the active cell
  560. // on Sheet1!J60:
  561. //
  562. // xlsx.SetPanes("Sheet1", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"topLeftCell":"N57","activePane":"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"}]}`)
  563. //
  564. // An example of how to unfreeze and remove all panes on Sheet1:
  565. //
  566. // xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  567. //
  568. func (f *File) SetPanes(sheet, panes string) {
  569. fs := parseFormatPanesSet(panes)
  570. xlsx := f.workSheetReader(sheet)
  571. p := &xlsxPane{
  572. ActivePane: fs.ActivePane,
  573. TopLeftCell: fs.TopLeftCell,
  574. XSplit: float64(fs.XSplit),
  575. YSplit: float64(fs.YSplit),
  576. }
  577. if fs.Freeze {
  578. p.State = "frozen"
  579. }
  580. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  581. if !(fs.Freeze) && !(fs.Split) {
  582. if len(xlsx.SheetViews.SheetView) > 0 {
  583. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  584. }
  585. }
  586. s := []*xlsxSelection{}
  587. for _, p := range fs.Panes {
  588. s = append(s, &xlsxSelection{
  589. ActiveCell: p.ActiveCell,
  590. Pane: p.Pane,
  591. SQRef: p.SQRef,
  592. })
  593. }
  594. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  595. }
  596. // GetSheetVisible provides function to get worksheet visible by given worksheet
  597. // name. For example, get visible state of Sheet1:
  598. //
  599. // xlsx.GetSheetVisible("Sheet1")
  600. //
  601. func (f *File) GetSheetVisible(name string) bool {
  602. content := f.workbookReader()
  603. visible := false
  604. for k, v := range content.Sheets.Sheet {
  605. if v.Name == trimSheetName(name) {
  606. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  607. visible = true
  608. }
  609. }
  610. }
  611. return visible
  612. }
  613. // trimSheetName provides function to trim invaild characters by given worksheet
  614. // name.
  615. func trimSheetName(name string) string {
  616. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  617. name = r.Replace(name)
  618. if utf8.RuneCountInString(name) > 31 {
  619. name = string([]rune(name)[0:31])
  620. }
  621. return name
  622. }