sheet.go 23 KB

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