sheet.go 23 KB

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