sheet.go 24 KB

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