sheet.go 22 KB

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