sheet.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "errors"
  7. "os"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "unicode/utf8"
  12. )
  13. // NewSheet provides function to create a new sheet by given 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", 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", replaceRelationshipsNameSpaceBytes(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, replaceWorkSheetsRelationshipsNameSpaceBytes(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", 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", []byte(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. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  186. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  187. 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">`)
  188. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  189. }
  190. // SetActiveSheet provides function to set default active worksheet of XLSX by
  191. // given index. Note that active index is different with the index that got by
  192. // function GetSheetMap, and it should be greater than 0 and less than total
  193. // worksheet numbers.
  194. func (f *File) SetActiveSheet(index int) {
  195. if index < 1 {
  196. index = 1
  197. }
  198. index--
  199. content := f.workbookReader()
  200. if len(content.BookViews.WorkBookView) > 0 {
  201. content.BookViews.WorkBookView[0].ActiveTab = index
  202. } else {
  203. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  204. ActiveTab: index,
  205. })
  206. }
  207. index++
  208. for idx, name := range f.GetSheetMap() {
  209. xlsx := f.workSheetReader(name)
  210. if index == idx {
  211. if len(xlsx.SheetViews.SheetView) > 0 {
  212. xlsx.SheetViews.SheetView[0].TabSelected = true
  213. } else {
  214. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  215. TabSelected: true,
  216. })
  217. }
  218. } else {
  219. if len(xlsx.SheetViews.SheetView) > 0 {
  220. xlsx.SheetViews.SheetView[0].TabSelected = false
  221. }
  222. }
  223. }
  224. }
  225. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  226. // found the active sheet will be return integer 0.
  227. func (f *File) GetActiveSheetIndex() int {
  228. buffer := bytes.Buffer{}
  229. content := f.workbookReader()
  230. for _, v := range content.Sheets.Sheet {
  231. xlsx := xlsxWorksheet{}
  232. buffer.WriteString("xl/worksheets/sheet")
  233. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  234. buffer.WriteString(".xml")
  235. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  236. for _, sheetView := range xlsx.SheetViews.SheetView {
  237. if sheetView.TabSelected {
  238. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  239. return ID
  240. }
  241. }
  242. buffer.Reset()
  243. }
  244. return 0
  245. }
  246. // SetSheetName provides function to set the worksheet name be given old and new
  247. // worksheet name. Maximum 31 characters are allowed in sheet title and this
  248. // function only changes the name of the sheet and will not update the sheet
  249. // name in the formula or reference associated with the cell. So there may be
  250. // problem formula error or reference missing.
  251. func (f *File) SetSheetName(oldName, newName string) {
  252. oldName = trimSheetName(oldName)
  253. newName = trimSheetName(newName)
  254. content := f.workbookReader()
  255. for k, v := range content.Sheets.Sheet {
  256. if v.Name == oldName {
  257. content.Sheets.Sheet[k].Name = newName
  258. f.sheetMap[newName] = f.sheetMap[oldName]
  259. delete(f.sheetMap, oldName)
  260. }
  261. }
  262. }
  263. // GetSheetName provides function to get worksheet name of XLSX by given
  264. // worksheet index. If given sheet index is invalid, will return an empty
  265. // string.
  266. func (f *File) GetSheetName(index int) string {
  267. content := f.workbookReader()
  268. rels := f.workbookRelsReader()
  269. for _, rel := range rels.Relationships {
  270. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  271. if rID == index {
  272. for _, v := range content.Sheets.Sheet {
  273. if v.ID == rel.ID {
  274. return v.Name
  275. }
  276. }
  277. }
  278. }
  279. return ""
  280. }
  281. // GetSheetIndex provides function to get worksheet index of XLSX by given sheet
  282. // name. If given worksheet name is invalid, will return an integer type value
  283. // 0.
  284. func (f *File) GetSheetIndex(name string) int {
  285. content := f.workbookReader()
  286. rels := f.workbookRelsReader()
  287. for _, v := range content.Sheets.Sheet {
  288. if v.Name == name {
  289. for _, rel := range rels.Relationships {
  290. if v.ID == rel.ID {
  291. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  292. return rID
  293. }
  294. }
  295. }
  296. }
  297. return 0
  298. }
  299. // GetSheetMap provides function to get worksheet name and index map of XLSX.
  300. // For example:
  301. //
  302. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  303. // if err != nil {
  304. // return
  305. // }
  306. // for index, name := range xlsx.GetSheetMap() {
  307. // fmt.Println(index, name)
  308. // }
  309. //
  310. func (f *File) GetSheetMap() map[int]string {
  311. content := f.workbookReader()
  312. rels := f.workbookRelsReader()
  313. sheetMap := map[int]string{}
  314. for _, v := range content.Sheets.Sheet {
  315. for _, rel := range rels.Relationships {
  316. if rel.ID == v.ID {
  317. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  318. sheetMap[rID] = v.Name
  319. }
  320. }
  321. }
  322. return sheetMap
  323. }
  324. // getSheetMap provides function to get worksheet name and XML file path map of
  325. // XLSX.
  326. func (f *File) getSheetMap() map[string]string {
  327. maps := make(map[string]string)
  328. for idx, name := range f.GetSheetMap() {
  329. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  330. }
  331. return maps
  332. }
  333. // SetSheetBackground provides function to set background picture by given
  334. // worksheet name.
  335. func (f *File) SetSheetBackground(sheet, picture string) error {
  336. var err error
  337. // Check picture exists first.
  338. if _, err = os.Stat(picture); os.IsNotExist(err) {
  339. return err
  340. }
  341. ext, ok := supportImageTypes[path.Ext(picture)]
  342. if !ok {
  343. return errors.New("Unsupported image extension")
  344. }
  345. pictureID := f.countMedia() + 1
  346. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  347. f.addSheetPicture(sheet, rID)
  348. f.addMedia(picture, ext)
  349. f.setContentTypePartImageExtensions()
  350. return err
  351. }
  352. // DeleteSheet provides function to delete worksheet in a workbook by given
  353. // worksheet name. Use this method with caution, which will affect changes in
  354. // references such as formulas, charts, and so on. If there is any referenced
  355. // value of the deleted worksheet, it will cause a file error when you open it.
  356. // This function will be invalid when only the one worksheet is left.
  357. func (f *File) DeleteSheet(name string) {
  358. content := f.workbookReader()
  359. for k, v := range content.Sheets.Sheet {
  360. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  361. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  362. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  363. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  364. target := f.deleteSheetFromWorkbookRels(v.ID)
  365. f.deleteSheetFromContentTypes(target)
  366. delete(f.sheetMap, name)
  367. delete(f.XLSX, sheet)
  368. delete(f.XLSX, rels)
  369. delete(f.Sheet, sheet)
  370. f.SheetCount--
  371. }
  372. }
  373. f.SetActiveSheet(len(f.GetSheetMap()))
  374. }
  375. // deleteSheetFromWorkbookRels provides function to remove worksheet
  376. // relationships by given relationships ID in the file
  377. // xl/_rels/workbook.xml.rels.
  378. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  379. content := f.workbookRelsReader()
  380. for k, v := range content.Relationships {
  381. if v.ID == rID {
  382. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  383. return v.Target
  384. }
  385. }
  386. return ""
  387. }
  388. // deleteSheetFromContentTypes provides function to remove worksheet
  389. // relationships by given target name in the file [Content_Types].xml.
  390. func (f *File) deleteSheetFromContentTypes(target string) {
  391. content := f.contentTypesReader()
  392. for k, v := range content.Overrides {
  393. if v.PartName == "/xl/"+target {
  394. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  395. }
  396. }
  397. }
  398. // CopySheet provides function to duplicate a worksheet by gave source and
  399. // target worksheet index. Note that currently doesn't support duplicate
  400. // workbooks that contain tables, charts or pictures. For Example:
  401. //
  402. // // Sheet1 already exists...
  403. // index := xlsx.NewSheet("Sheet2")
  404. // err := xlsx.CopySheet(1, index)
  405. // return err
  406. //
  407. func (f *File) CopySheet(from, to int) error {
  408. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  409. return errors.New("Invalid worksheet index")
  410. }
  411. f.copySheet(from, to)
  412. return nil
  413. }
  414. // copySheet provides function to duplicate a worksheet by gave source and
  415. // target worksheet name.
  416. func (f *File) copySheet(from, to int) {
  417. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  418. worksheet := xlsxWorksheet{}
  419. deepCopy(&worksheet, &sheet)
  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. }
  435. // SetSheetVisible provides function to set worksheet visible by given worksheet
  436. // name. A workbook must contain at least one visible worksheet. If the given
  437. // worksheet has been activated, this setting will be invalidated. Sheet state
  438. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  439. //
  440. // visible
  441. // hidden
  442. // veryHidden
  443. //
  444. // For example, hide Sheet1:
  445. //
  446. // xlsx.SetSheetVisible("Sheet1", false)
  447. //
  448. func (f *File) SetSheetVisible(name string, visible bool) {
  449. name = trimSheetName(name)
  450. content := f.workbookReader()
  451. if visible {
  452. for k, v := range content.Sheets.Sheet {
  453. if v.Name == name {
  454. content.Sheets.Sheet[k].State = ""
  455. }
  456. }
  457. return
  458. }
  459. count := 0
  460. for _, v := range content.Sheets.Sheet {
  461. if v.State != "hidden" {
  462. count++
  463. }
  464. }
  465. for k, v := range content.Sheets.Sheet {
  466. xlsx := f.workSheetReader(f.GetSheetMap()[k])
  467. tabSelected := false
  468. if len(xlsx.SheetViews.SheetView) > 0 {
  469. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  470. }
  471. if v.Name == name && count > 1 && !tabSelected {
  472. content.Sheets.Sheet[k].State = "hidden"
  473. }
  474. }
  475. }
  476. // parseFormatPanesSet provides function to parse the panes settings.
  477. func parseFormatPanesSet(formatSet string) *formatPanes {
  478. format := formatPanes{}
  479. json.Unmarshal([]byte(formatSet), &format)
  480. return &format
  481. }
  482. // SetPanes provides function to create and remove freeze panes and split panes
  483. // by given worksheet name and panes format set.
  484. //
  485. // activePane defines the pane that is active. The possible values for this
  486. // attribute are defined in the following table:
  487. //
  488. // Enumeration Value | Description
  489. // --------------------------------+-------------------------------------------------------------
  490. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  491. // | splits are applied.
  492. // |
  493. // | This value is also used when only a horizontal split has
  494. // | been applied, dividing the pane into upper and lower
  495. // | regions. In that case, this value specifies the bottom
  496. // | pane.
  497. // |
  498. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  499. // | splits are applied.
  500. // |
  501. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  502. // | are applied.
  503. // |
  504. // | This value is also used when only a horizontal split has
  505. // | been applied, dividing the pane into upper and lower
  506. // | regions. In that case, this value specifies the top pane.
  507. // |
  508. // | This value is also used when only a vertical split has
  509. // | been applied, dividing the pane into right and left
  510. // | regions. In that case, this value specifies the left pane
  511. // |
  512. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  513. // | splits are applied.
  514. // |
  515. // | This value is also used when only a vertical split has
  516. // | been applied, dividing the pane into right and left
  517. // | regions. In that case, this value specifies the right
  518. // | pane.
  519. //
  520. // Pane state type is restricted to the values supported currently listed in the following table:
  521. //
  522. // Enumeration Value | Description
  523. // --------------------------------+-------------------------------------------------------------
  524. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  525. // | this state, when the panes are unfrozen again, a single
  526. // | pane results, with no split.
  527. // |
  528. // | In this state, the split bars are not adjustable.
  529. // |
  530. // split (Split) | Panes are split, but not frozen. In this state, the split
  531. // | bars are adjustable by the user.
  532. //
  533. // x_split (Horizontal Split Position): Horizontal position of the split, in
  534. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  535. // indicates the number of columns visible in the top pane.
  536. //
  537. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  538. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  539. // number of rows visible in the left pane. The possible values for this
  540. // attribute are defined by the W3C XML Schema double datatype.
  541. //
  542. // top_left_cell: Location of the top left visible cell in the bottom right pane
  543. // (when in Left-To-Right mode).
  544. //
  545. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  546. // set of ranges.
  547. //
  548. // An example of how to freeze column A in the Sheet1 and set the active cell on
  549. // Sheet1!K16:
  550. //
  551. // 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"}]}`)
  552. //
  553. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  554. // ranges on Sheet1!A11:XFD11:
  555. //
  556. // 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"}]}`)
  557. //
  558. // An example of how to create split panes in the Sheet1 and set the active cell
  559. // on Sheet1!J60:
  560. //
  561. // 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"}]}`)
  562. //
  563. // An example of how to unfreeze and remove all panes on Sheet1:
  564. //
  565. // xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  566. //
  567. func (f *File) SetPanes(sheet, panes string) {
  568. fs := parseFormatPanesSet(panes)
  569. xlsx := f.workSheetReader(sheet)
  570. p := &xlsxPane{
  571. ActivePane: fs.ActivePane,
  572. TopLeftCell: fs.TopLeftCell,
  573. XSplit: float64(fs.XSplit),
  574. YSplit: float64(fs.YSplit),
  575. }
  576. if fs.Freeze {
  577. p.State = "frozen"
  578. }
  579. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  580. if !(fs.Freeze) && !(fs.Split) {
  581. if len(xlsx.SheetViews.SheetView) > 0 {
  582. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  583. }
  584. }
  585. s := []*xlsxSelection{}
  586. for _, p := range fs.Panes {
  587. s = append(s, &xlsxSelection{
  588. ActiveCell: p.ActiveCell,
  589. Pane: p.Pane,
  590. SQRef: p.SQRef,
  591. })
  592. }
  593. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  594. }
  595. // GetSheetVisible provides function to get worksheet visible by given worksheet
  596. // name. For example, get visible state of Sheet1:
  597. //
  598. // xlsx.GetSheetVisible("Sheet1")
  599. //
  600. func (f *File) GetSheetVisible(name string) bool {
  601. content := f.workbookReader()
  602. visible := false
  603. for k, v := range content.Sheets.Sheet {
  604. if v.Name == trimSheetName(name) {
  605. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  606. visible = true
  607. }
  608. }
  609. }
  610. return visible
  611. }
  612. // trimSheetName provides function to trim invaild characters by given worksheet
  613. // name.
  614. func trimSheetName(name string) string {
  615. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  616. name = r.Replace(name)
  617. if utf8.RuneCountInString(name) > 31 {
  618. name = string([]rune(name)[0:31])
  619. }
  620. return name
  621. }