sheet.go 24 KB

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