sheet.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 worksheet name,
  14. // when creating a new XLSX file, the default sheet will be create, when you
  15. // create a new file.
  16. func (f *File) NewSheet(name string) int {
  17. // Check if the worksheet already exists
  18. if f.GetSheetIndex(name) != 0 {
  19. return f.SheetCount
  20. }
  21. f.SheetCount++
  22. // Update docProps/app.xml
  23. f.setAppXML()
  24. // Update [Content_Types].xml
  25. f.setContentTypes(f.SheetCount)
  26. // Create new sheet /xl/worksheets/sheet%d.xml
  27. f.setSheet(f.SheetCount, name)
  28. // Update xl/_rels/workbook.xml.rels
  29. rID := f.addXlsxWorkbookRels(f.SheetCount)
  30. // Update xl/workbook.xml
  31. f.setWorkbook(name, rID)
  32. return f.SheetCount
  33. }
  34. // contentTypesReader provides function to get the pointer to the
  35. // [Content_Types].xml structure after deserialization.
  36. func (f *File) contentTypesReader() *xlsxTypes {
  37. if f.ContentTypes == nil {
  38. var content xlsxTypes
  39. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  40. f.ContentTypes = &content
  41. }
  42. return f.ContentTypes
  43. }
  44. // contentTypesWriter provides function to save [Content_Types].xml after
  45. // serialize structure.
  46. func (f *File) contentTypesWriter() {
  47. if f.ContentTypes != nil {
  48. output, _ := xml.Marshal(f.ContentTypes)
  49. f.saveFileList("[Content_Types].xml", string(output))
  50. }
  51. }
  52. // workbookReader provides function to get the pointer to the xl/workbook.xml
  53. // structure after deserialization.
  54. func (f *File) workbookReader() *xlsxWorkbook {
  55. if f.WorkBook == nil {
  56. var content xlsxWorkbook
  57. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  58. f.WorkBook = &content
  59. }
  60. return f.WorkBook
  61. }
  62. // workbookWriter provides function to save xl/workbook.xml after serialize
  63. // structure.
  64. func (f *File) workbookWriter() {
  65. if f.WorkBook != nil {
  66. output, _ := xml.Marshal(f.WorkBook)
  67. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  68. }
  69. }
  70. // worksheetWriter provides function to save xl/worksheets/sheet%d.xml after
  71. // serialize structure.
  72. func (f *File) worksheetWriter() {
  73. for path, sheet := range f.Sheet {
  74. if sheet != nil {
  75. for k, v := range sheet.SheetData.Row {
  76. f.Sheet[path].SheetData.Row[k].C = trimCell(v.C)
  77. }
  78. output, _ := xml.Marshal(sheet)
  79. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  80. ok := f.checked[path]
  81. if ok {
  82. f.checked[path] = false
  83. }
  84. }
  85. }
  86. }
  87. // trimCell provides function to trim blank cells which created by completeCol.
  88. func trimCell(column []xlsxC) []xlsxC {
  89. col := []xlsxC{}
  90. for _, c := range column {
  91. if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
  92. col = append(col, c)
  93. }
  94. }
  95. return col
  96. }
  97. // Read and update property of contents type of XLSX.
  98. func (f *File) setContentTypes(index int) {
  99. content := f.contentTypesReader()
  100. content.Overrides = append(content.Overrides, xlsxOverride{
  101. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  102. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  103. })
  104. }
  105. // Update sheet property by given index.
  106. func (f *File) setSheet(index int, name string) {
  107. var xlsx xlsxWorksheet
  108. xlsx.Dimension.Ref = "A1"
  109. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  110. WorkbookViewID: 0,
  111. })
  112. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  113. f.sheetMap[trimSheetName(name)] = path
  114. f.Sheet[path] = &xlsx
  115. }
  116. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  117. // allowed in sheet title.
  118. func (f *File) setWorkbook(name string, rid int) {
  119. content := f.workbookReader()
  120. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  121. Name: trimSheetName(name),
  122. SheetID: strconv.Itoa(rid),
  123. ID: "rId" + strconv.Itoa(rid),
  124. })
  125. }
  126. // workbookRelsReader provides function to read and unmarshal workbook
  127. // relationships of XLSX file.
  128. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  129. if f.WorkBookRels == nil {
  130. var content xlsxWorkbookRels
  131. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  132. f.WorkBookRels = &content
  133. }
  134. return f.WorkBookRels
  135. }
  136. // workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
  137. // serialize structure.
  138. func (f *File) workbookRelsWriter() {
  139. if f.WorkBookRels != nil {
  140. output, _ := xml.Marshal(f.WorkBookRels)
  141. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  142. }
  143. }
  144. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  145. func (f *File) addXlsxWorkbookRels(sheet int) int {
  146. content := f.workbookRelsReader()
  147. rID := 0
  148. for _, v := range content.Relationships {
  149. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  150. if t > rID {
  151. rID = t
  152. }
  153. }
  154. rID++
  155. ID := bytes.Buffer{}
  156. ID.WriteString("rId")
  157. ID.WriteString(strconv.Itoa(rID))
  158. target := bytes.Buffer{}
  159. target.WriteString("worksheets/sheet")
  160. target.WriteString(strconv.Itoa(sheet))
  161. target.WriteString(".xml")
  162. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  163. ID: ID.String(),
  164. Target: target.String(),
  165. Type: SourceRelationshipWorkSheet,
  166. })
  167. return rID
  168. }
  169. // setAppXML update docProps/app.xml file of XML.
  170. func (f *File) setAppXML() {
  171. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  172. }
  173. // Some tools that read XLSX files have very strict requirements about the
  174. // structure of the input XML. In particular both Numbers on the Mac and SAS
  175. // dislike inline XML namespace declarations, or namespace prefixes that don't
  176. // match the ones that Excel itself uses. This is a problem because the Go XML
  177. // library doesn't multiple namespace declarations in a single element of a
  178. // document. This function is a horrible hack to fix that after the XML
  179. // marshalling is completed.
  180. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  181. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  182. 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">`
  183. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  184. }
  185. // SetActiveSheet provides function to set default active worksheet of XLSX by
  186. // given index. Note that active index is different with the index that got by
  187. // function GetSheetMap, and it should be greater than 0 and less than total
  188. // worksheet numbers.
  189. func (f *File) SetActiveSheet(index int) {
  190. if index < 1 {
  191. index = 1
  192. }
  193. index--
  194. content := f.workbookReader()
  195. if len(content.BookViews.WorkBookView) > 0 {
  196. content.BookViews.WorkBookView[0].ActiveTab = index
  197. } else {
  198. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  199. ActiveTab: index,
  200. })
  201. }
  202. index++
  203. for idx, name := range f.GetSheetMap() {
  204. xlsx := f.workSheetReader(name)
  205. if index == idx {
  206. if len(xlsx.SheetViews.SheetView) > 0 {
  207. xlsx.SheetViews.SheetView[0].TabSelected = true
  208. } else {
  209. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  210. TabSelected: true,
  211. })
  212. }
  213. } else {
  214. if len(xlsx.SheetViews.SheetView) > 0 {
  215. xlsx.SheetViews.SheetView[0].TabSelected = false
  216. }
  217. }
  218. }
  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 worksheet name be given old and new
  242. // worksheet 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. f.sheetMap[newName] = f.sheetMap[oldName]
  254. delete(f.sheetMap, oldName)
  255. }
  256. }
  257. }
  258. // GetSheetName provides function to get worksheet name of XLSX by given
  259. // worksheet index. If given sheet index is invalid, will return an empty
  260. // string.
  261. func (f *File) GetSheetName(index int) string {
  262. content := f.workbookReader()
  263. rels := f.workbookRelsReader()
  264. for _, rel := range rels.Relationships {
  265. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  266. if rID == index {
  267. for _, v := range content.Sheets.Sheet {
  268. if v.ID == rel.ID {
  269. return v.Name
  270. }
  271. }
  272. }
  273. }
  274. return ""
  275. }
  276. // GetSheetIndex provides function to get worksheet index of XLSX by given sheet
  277. // name. If given worksheet name is invalid, will return an integer type value
  278. // 0.
  279. func (f *File) GetSheetIndex(name string) int {
  280. content := f.workbookReader()
  281. rels := f.workbookRelsReader()
  282. for _, v := range content.Sheets.Sheet {
  283. if v.Name == name {
  284. for _, rel := range rels.Relationships {
  285. if v.ID == rel.ID {
  286. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  287. return rID
  288. }
  289. }
  290. }
  291. }
  292. return 0
  293. }
  294. // GetSheetMap provides function to get worksheet name and index map of XLSX.
  295. // For example:
  296. //
  297. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  298. // if err != nil {
  299. // return
  300. // }
  301. // for index, name := range xlsx.GetSheetMap() {
  302. // fmt.Println(index, name)
  303. // }
  304. //
  305. func (f *File) GetSheetMap() map[int]string {
  306. content := f.workbookReader()
  307. rels := f.workbookRelsReader()
  308. sheetMap := map[int]string{}
  309. for _, v := range content.Sheets.Sheet {
  310. for _, rel := range rels.Relationships {
  311. if rel.ID == v.ID {
  312. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  313. sheetMap[rID] = v.Name
  314. }
  315. }
  316. }
  317. return sheetMap
  318. }
  319. // getSheetMap provides function to get worksheet name and XML file path map of
  320. // XLSX.
  321. func (f *File) getSheetMap() map[string]string {
  322. maps := make(map[string]string)
  323. for idx, name := range f.GetSheetMap() {
  324. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  325. }
  326. return maps
  327. }
  328. // SetSheetBackground provides function to set background picture by given
  329. // worksheet name.
  330. func (f *File) SetSheetBackground(sheet, picture string) error {
  331. var err error
  332. // Check picture exists first.
  333. if _, err = os.Stat(picture); os.IsNotExist(err) {
  334. return err
  335. }
  336. ext, ok := supportImageTypes[path.Ext(picture)]
  337. if !ok {
  338. return errors.New("Unsupported image extension")
  339. }
  340. pictureID := f.countMedia() + 1
  341. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  342. f.addSheetPicture(sheet, rID)
  343. f.addMedia(picture, ext)
  344. f.setContentTypePartImageExtensions()
  345. return err
  346. }
  347. // DeleteSheet provides function to delete worksheet in a workbook by given
  348. // worksheet name. Use this method with caution, which will affect changes in
  349. // references such as formulas, charts, and so on. If there is any referenced
  350. // value of the deleted worksheet, it will cause a file error when you open it.
  351. // This function will be invalid when only the one worksheet is left.
  352. func (f *File) DeleteSheet(name string) {
  353. content := f.workbookReader()
  354. for k, v := range content.Sheets.Sheet {
  355. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  356. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  357. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  358. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  359. target := f.deleteSheetFromWorkbookRels(v.ID)
  360. f.deleteSheetFromContentTypes(target)
  361. delete(f.sheetMap, name)
  362. delete(f.XLSX, sheet)
  363. delete(f.XLSX, rels)
  364. delete(f.Sheet, sheet)
  365. f.SheetCount--
  366. }
  367. }
  368. f.SetActiveSheet(len(f.GetSheetMap()))
  369. }
  370. // deleteSheetFromWorkbookRels provides function to remove worksheet
  371. // relationships by given relationships ID in the file
  372. // xl/_rels/workbook.xml.rels.
  373. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  374. content := f.workbookRelsReader()
  375. for k, v := range content.Relationships {
  376. if v.ID == rID {
  377. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  378. return v.Target
  379. }
  380. }
  381. return ""
  382. }
  383. // deleteSheetFromContentTypes provides function to remove worksheet
  384. // relationships by given target name in the file [Content_Types].xml.
  385. func (f *File) deleteSheetFromContentTypes(target string) {
  386. content := f.contentTypesReader()
  387. for k, v := range content.Overrides {
  388. if v.PartName == "/xl/"+target {
  389. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  390. }
  391. }
  392. }
  393. // CopySheet provides function to duplicate a worksheet by gave source and
  394. // target worksheet index. Note that currently doesn't support duplicate
  395. // workbooks that contain tables, charts or pictures. For Example:
  396. //
  397. // // Sheet1 already exists...
  398. // index := xlsx.NewSheet("Sheet2")
  399. // err := xlsx.CopySheet(1, index)
  400. // return err
  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 name.
  411. func (f *File) copySheet(from, to int) {
  412. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  413. worksheet := xlsxWorksheet{}
  414. deepCopy(&worksheet, &sheet)
  415. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  416. if len(worksheet.SheetViews.SheetView) > 0 {
  417. worksheet.SheetViews.SheetView[0].TabSelected = false
  418. }
  419. worksheet.Drawing = nil
  420. worksheet.TableParts = nil
  421. worksheet.PageSetUp = nil
  422. f.Sheet[path] = &worksheet
  423. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  424. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  425. _, ok := f.XLSX[fromRels]
  426. if ok {
  427. f.XLSX[toRels] = f.XLSX[fromRels]
  428. }
  429. }
  430. // SetSheetVisible provides function to set worksheet visible by given worksheet
  431. // name. A workbook must contain at least one visible worksheet. If the given
  432. // worksheet has been activated, this setting will be invalidated. Sheet state
  433. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  434. //
  435. // visible
  436. // hidden
  437. // veryHidden
  438. //
  439. // For example, hide Sheet1:
  440. //
  441. // xlsx.SetSheetVisible("Sheet1", false)
  442. //
  443. func (f *File) SetSheetVisible(name string, visible bool) {
  444. name = trimSheetName(name)
  445. content := f.workbookReader()
  446. if visible {
  447. for k, v := range content.Sheets.Sheet {
  448. if v.Name == name {
  449. content.Sheets.Sheet[k].State = ""
  450. }
  451. }
  452. return
  453. }
  454. count := 0
  455. for _, v := range content.Sheets.Sheet {
  456. if v.State != "hidden" {
  457. count++
  458. }
  459. }
  460. for k, v := range content.Sheets.Sheet {
  461. xlsx := f.workSheetReader(f.GetSheetMap()[k])
  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 name 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 utf8.RuneCountInString(name) > 31 {
  617. name = string([]rune(name)[0:31])
  618. }
  619. return name
  620. }