sheet.go 22 KB

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