sheet.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 := make([]xlsxC, len(column))
  90. i := 0
  91. for _, c := range column {
  92. if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
  93. col[i] = c
  94. i++
  95. }
  96. }
  97. return col[0:i]
  98. }
  99. // Read and update property of contents type of XLSX.
  100. func (f *File) setContentTypes(index int) {
  101. content := f.contentTypesReader()
  102. content.Overrides = append(content.Overrides, xlsxOverride{
  103. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  104. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  105. })
  106. }
  107. // Update sheet property by given index.
  108. func (f *File) setSheet(index int, name string) {
  109. var xlsx xlsxWorksheet
  110. xlsx.Dimension.Ref = "A1"
  111. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  112. WorkbookViewID: 0,
  113. })
  114. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  115. f.sheetMap[trimSheetName(name)] = path
  116. f.Sheet[path] = &xlsx
  117. }
  118. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  119. // allowed in sheet title.
  120. func (f *File) setWorkbook(name string, rid int) {
  121. content := f.workbookReader()
  122. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  123. Name: trimSheetName(name),
  124. SheetID: strconv.Itoa(rid),
  125. ID: "rId" + strconv.Itoa(rid),
  126. })
  127. }
  128. // workbookRelsReader provides function to read and unmarshal workbook
  129. // relationships of XLSX file.
  130. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  131. if f.WorkBookRels == nil {
  132. var content xlsxWorkbookRels
  133. _ = xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  134. f.WorkBookRels = &content
  135. }
  136. return f.WorkBookRels
  137. }
  138. // workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
  139. // serialize structure.
  140. func (f *File) workbookRelsWriter() {
  141. if f.WorkBookRels != nil {
  142. output, _ := xml.Marshal(f.WorkBookRels)
  143. f.saveFileList("xl/_rels/workbook.xml.rels", output)
  144. }
  145. }
  146. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  147. func (f *File) addXlsxWorkbookRels(sheet int) int {
  148. content := f.workbookRelsReader()
  149. rID := 0
  150. for _, v := range content.Relationships {
  151. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  152. if t > rID {
  153. rID = t
  154. }
  155. }
  156. rID++
  157. ID := bytes.Buffer{}
  158. ID.WriteString("rId")
  159. ID.WriteString(strconv.Itoa(rID))
  160. target := bytes.Buffer{}
  161. target.WriteString("worksheets/sheet")
  162. target.WriteString(strconv.Itoa(sheet))
  163. target.WriteString(".xml")
  164. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  165. ID: ID.String(),
  166. Target: target.String(),
  167. Type: SourceRelationshipWorkSheet,
  168. })
  169. return rID
  170. }
  171. // setAppXML update docProps/app.xml file of XML.
  172. func (f *File) setAppXML() {
  173. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  174. }
  175. // Some tools that read XLSX files have very strict requirements about the
  176. // structure of the input XML. In particular both Numbers on the Mac and SAS
  177. // dislike inline XML namespace declarations, or namespace prefixes that don't
  178. // match the ones that Excel itself uses. This is a problem because the Go XML
  179. // library doesn't multiple namespace declarations in a single element of a
  180. // document. This function is a horrible hack to fix that after the XML
  181. // marshalling is completed.
  182. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  183. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  184. 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">`)
  185. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  186. }
  187. // SetActiveSheet provides function to set default active worksheet of XLSX by
  188. // given index. Note that active index is different with the index that got by
  189. // function GetSheetMap, and it should be greater than 0 and less than total
  190. // worksheet numbers.
  191. func (f *File) SetActiveSheet(index int) {
  192. if index < 1 {
  193. index = 1
  194. }
  195. index--
  196. content := f.workbookReader()
  197. if len(content.BookViews.WorkBookView) > 0 {
  198. content.BookViews.WorkBookView[0].ActiveTab = index
  199. } else {
  200. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  201. ActiveTab: index,
  202. })
  203. }
  204. index++
  205. for idx, name := range f.GetSheetMap() {
  206. xlsx := f.workSheetReader(name)
  207. if index == idx {
  208. if len(xlsx.SheetViews.SheetView) > 0 {
  209. xlsx.SheetViews.SheetView[0].TabSelected = true
  210. } else {
  211. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  212. TabSelected: true,
  213. })
  214. }
  215. } else {
  216. if len(xlsx.SheetViews.SheetView) > 0 {
  217. xlsx.SheetViews.SheetView[0].TabSelected = false
  218. }
  219. }
  220. }
  221. }
  222. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  223. // found the active sheet will be return integer 0.
  224. func (f *File) GetActiveSheetIndex() int {
  225. buffer := bytes.Buffer{}
  226. content := f.workbookReader()
  227. for _, v := range content.Sheets.Sheet {
  228. xlsx := xlsxWorksheet{}
  229. buffer.WriteString("xl/worksheets/sheet")
  230. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  231. buffer.WriteString(".xml")
  232. _ = xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  233. for _, sheetView := range xlsx.SheetViews.SheetView {
  234. if sheetView.TabSelected {
  235. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  236. return ID
  237. }
  238. }
  239. buffer.Reset()
  240. }
  241. return 0
  242. }
  243. // SetSheetName provides function to set the worksheet name be given old and new
  244. // worksheet name. Maximum 31 characters are allowed in sheet title and this
  245. // function only changes the name of the sheet and will not update the sheet
  246. // name in the formula or reference associated with the cell. So there may be
  247. // problem formula error or reference missing.
  248. func (f *File) SetSheetName(oldName, newName string) {
  249. oldName = trimSheetName(oldName)
  250. newName = trimSheetName(newName)
  251. content := f.workbookReader()
  252. for k, v := range content.Sheets.Sheet {
  253. if v.Name == oldName {
  254. content.Sheets.Sheet[k].Name = newName
  255. f.sheetMap[newName] = f.sheetMap[oldName]
  256. delete(f.sheetMap, oldName)
  257. }
  258. }
  259. }
  260. // GetSheetName provides function to get worksheet name of XLSX by given
  261. // worksheet index. If given sheet index is invalid, will return an empty
  262. // string.
  263. func (f *File) GetSheetName(index int) string {
  264. content := f.workbookReader()
  265. rels := f.workbookRelsReader()
  266. for _, rel := range rels.Relationships {
  267. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  268. if rID == index {
  269. for _, v := range content.Sheets.Sheet {
  270. if v.ID == rel.ID {
  271. return v.Name
  272. }
  273. }
  274. }
  275. }
  276. return ""
  277. }
  278. // GetSheetIndex provides function to get worksheet index of XLSX by given sheet
  279. // name. If given worksheet name is invalid, will return an integer type value
  280. // 0.
  281. func (f *File) GetSheetIndex(name string) int {
  282. content := f.workbookReader()
  283. rels := f.workbookRelsReader()
  284. for _, v := range content.Sheets.Sheet {
  285. if v.Name == name {
  286. for _, rel := range rels.Relationships {
  287. if v.ID == rel.ID {
  288. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  289. return rID
  290. }
  291. }
  292. }
  293. }
  294. return 0
  295. }
  296. // GetSheetMap provides function to get worksheet name and index map of XLSX.
  297. // For example:
  298. //
  299. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  300. // if err != nil {
  301. // return
  302. // }
  303. // for index, name := range xlsx.GetSheetMap() {
  304. // fmt.Println(index, name)
  305. // }
  306. //
  307. func (f *File) GetSheetMap() map[int]string {
  308. content := f.workbookReader()
  309. rels := f.workbookRelsReader()
  310. sheetMap := map[int]string{}
  311. for _, v := range content.Sheets.Sheet {
  312. for _, rel := range rels.Relationships {
  313. if rel.ID == v.ID {
  314. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  315. sheetMap[rID] = v.Name
  316. }
  317. }
  318. }
  319. return sheetMap
  320. }
  321. // getSheetMap provides function to get worksheet name and XML file path map of
  322. // XLSX.
  323. func (f *File) getSheetMap() map[string]string {
  324. maps := make(map[string]string)
  325. for idx, name := range f.GetSheetMap() {
  326. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  327. }
  328. return maps
  329. }
  330. // SetSheetBackground provides function to set background picture by given
  331. // worksheet name.
  332. func (f *File) SetSheetBackground(sheet, picture string) error {
  333. var err error
  334. // Check picture exists first.
  335. if _, err = os.Stat(picture); os.IsNotExist(err) {
  336. return err
  337. }
  338. ext, ok := supportImageTypes[path.Ext(picture)]
  339. if !ok {
  340. return errors.New("Unsupported image extension")
  341. }
  342. pictureID := f.countMedia() + 1
  343. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  344. f.addSheetPicture(sheet, rID)
  345. f.addMedia(picture, ext)
  346. f.setContentTypePartImageExtensions()
  347. return err
  348. }
  349. // DeleteSheet provides function to delete worksheet in a workbook by given
  350. // worksheet name. Use this method with caution, which will affect changes in
  351. // references such as formulas, charts, and so on. If there is any referenced
  352. // value of the deleted worksheet, it will cause a file error when you open it.
  353. // This function will be invalid when only the one worksheet is left.
  354. func (f *File) DeleteSheet(name string) {
  355. content := f.workbookReader()
  356. for k, v := range content.Sheets.Sheet {
  357. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  358. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  359. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  360. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  361. target := f.deleteSheetFromWorkbookRels(v.ID)
  362. f.deleteSheetFromContentTypes(target)
  363. delete(f.sheetMap, name)
  364. delete(f.XLSX, sheet)
  365. delete(f.XLSX, rels)
  366. delete(f.Sheet, sheet)
  367. f.SheetCount--
  368. }
  369. }
  370. f.SetActiveSheet(len(f.GetSheetMap()))
  371. }
  372. // deleteSheetFromWorkbookRels provides function to remove worksheet
  373. // relationships by given relationships ID in the file
  374. // xl/_rels/workbook.xml.rels.
  375. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  376. content := f.workbookRelsReader()
  377. for k, v := range content.Relationships {
  378. if v.ID == rID {
  379. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  380. return v.Target
  381. }
  382. }
  383. return ""
  384. }
  385. // deleteSheetFromContentTypes provides function to remove worksheet
  386. // relationships by given target name in the file [Content_Types].xml.
  387. func (f *File) deleteSheetFromContentTypes(target string) {
  388. content := f.contentTypesReader()
  389. for k, v := range content.Overrides {
  390. if v.PartName == "/xl/"+target {
  391. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  392. }
  393. }
  394. }
  395. // CopySheet provides function to duplicate a worksheet by gave source and
  396. // target worksheet index. Note that currently doesn't support duplicate
  397. // workbooks that contain tables, charts or pictures. For Example:
  398. //
  399. // // Sheet1 already exists...
  400. // index := xlsx.NewSheet("Sheet2")
  401. // err := xlsx.CopySheet(1, index)
  402. // return err
  403. //
  404. func (f *File) CopySheet(from, to int) error {
  405. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  406. return errors.New("Invalid worksheet index")
  407. }
  408. return f.copySheet(from, to)
  409. }
  410. // copySheet provides function to duplicate a worksheet by gave source and
  411. // target worksheet name.
  412. func (f *File) copySheet(from, to int) error {
  413. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  414. worksheet := xlsxWorksheet{}
  415. err := deepCopy(&worksheet, &sheet)
  416. if err != nil {
  417. return err
  418. }
  419. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  420. if len(worksheet.SheetViews.SheetView) > 0 {
  421. worksheet.SheetViews.SheetView[0].TabSelected = false
  422. }
  423. worksheet.Drawing = nil
  424. worksheet.TableParts = nil
  425. worksheet.PageSetUp = nil
  426. f.Sheet[path] = &worksheet
  427. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  428. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  429. _, ok := f.XLSX[fromRels]
  430. if ok {
  431. f.XLSX[toRels] = f.XLSX[fromRels]
  432. }
  433. return err
  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, error) {
  478. format := formatPanes{}
  479. err := json.Unmarshal([]byte(formatSet), &format)
  480. return &format, err
  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 := []rune{}
  616. for _, v := range name {
  617. switch v {
  618. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  619. continue
  620. default:
  621. r = append(r, v)
  622. }
  623. }
  624. name = string(r)
  625. if utf8.RuneCountInString(name) > 31 {
  626. name = string([]rune(name)[0:31])
  627. }
  628. return name
  629. }