sheet.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "strconv"
  20. "strings"
  21. "unicode/utf8"
  22. "github.com/mohae/deepcopy"
  23. )
  24. // NewSheet provides function to create a new sheet by given worksheet name.
  25. // When creating a new XLSX file, the default sheet will be created. Returns
  26. // the number of sheets in the workbook (file) after appending the new sheet.
  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(namespaceStrictToTransitional(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(namespaceStrictToTransitional(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. // setContentTypes; 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. // setSheet; 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(namespaceStrictToTransitional(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. // replaceRelationshipsNameSpaceBytes; 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 function to set default active worksheet of XLSX by
  207. // given index. Note that active index is different from the index returned by
  208. // function GetSheetMap(). 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 index of the
  242. // XLSX. If not 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(namespaceStrictToTransitional(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. relStr := strings.SplitN(rel.Target, "worksheets/sheet", 2)
  333. if rel.ID == v.ID && len(relStr) == 2 {
  334. rID, _ := strconv.Atoi(strings.TrimSuffix(relStr[1], ".xml"))
  335. sheetMap[rID] = v.Name
  336. }
  337. }
  338. }
  339. return sheetMap
  340. }
  341. // getSheetMap provides a function to get worksheet name and XML file path map of
  342. // XLSX.
  343. func (f *File) getSheetMap() map[string]string {
  344. maps := make(map[string]string)
  345. for idx, name := range f.GetSheetMap() {
  346. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  347. }
  348. return maps
  349. }
  350. // SetSheetBackground provides a function to set background picture by given
  351. // worksheet name and file path.
  352. func (f *File) SetSheetBackground(sheet, picture string) error {
  353. var err error
  354. // Check picture exists first.
  355. if _, err = os.Stat(picture); os.IsNotExist(err) {
  356. return err
  357. }
  358. ext, ok := supportImageTypes[path.Ext(picture)]
  359. if !ok {
  360. return errors.New("unsupported image extension")
  361. }
  362. pictureID := f.countMedia() + 1
  363. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  364. f.addSheetPicture(sheet, rID)
  365. file, _ := ioutil.ReadFile(picture)
  366. f.addMedia(file, ext)
  367. f.setContentTypePartImageExtensions()
  368. return err
  369. }
  370. // DeleteSheet provides a function to delete worksheet in a workbook by given
  371. // worksheet name. Use this method with caution, which will affect changes in
  372. // references such as formulas, charts, and so on. If there is any referenced
  373. // value of the deleted worksheet, it will cause a file error when you open it.
  374. // This function will be invalid when only the one worksheet is left.
  375. func (f *File) DeleteSheet(name string) {
  376. content := f.workbookReader()
  377. for k, v := range content.Sheets.Sheet {
  378. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  379. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  380. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  381. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  382. target := f.deleteSheetFromWorkbookRels(v.ID)
  383. f.deleteSheetFromContentTypes(target)
  384. delete(f.sheetMap, name)
  385. delete(f.XLSX, sheet)
  386. delete(f.XLSX, rels)
  387. delete(f.Sheet, sheet)
  388. f.SheetCount--
  389. }
  390. }
  391. f.SetActiveSheet(len(f.GetSheetMap()))
  392. }
  393. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  394. // relationships by given relationships ID in the file
  395. // xl/_rels/workbook.xml.rels.
  396. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  397. content := f.workbookRelsReader()
  398. for k, v := range content.Relationships {
  399. if v.ID == rID {
  400. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  401. return v.Target
  402. }
  403. }
  404. return ""
  405. }
  406. // deleteSheetFromContentTypes provides a function to remove worksheet
  407. // relationships by given target name in the file [Content_Types].xml.
  408. func (f *File) deleteSheetFromContentTypes(target string) {
  409. content := f.contentTypesReader()
  410. for k, v := range content.Overrides {
  411. if v.PartName == "/xl/"+target {
  412. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  413. }
  414. }
  415. }
  416. // CopySheet provides a function to duplicate a worksheet by gave source and
  417. // target worksheet index. Note that currently doesn't support duplicate
  418. // workbooks that contain tables, charts or pictures. For Example:
  419. //
  420. // // Sheet1 already exists...
  421. // index := xlsx.NewSheet("Sheet2")
  422. // err := xlsx.CopySheet(1, index)
  423. // return err
  424. //
  425. func (f *File) CopySheet(from, to int) error {
  426. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  427. return errors.New("invalid worksheet index")
  428. }
  429. f.copySheet(from, to)
  430. return nil
  431. }
  432. // copySheet provides a function to duplicate a worksheet by gave source and
  433. // target worksheet name.
  434. func (f *File) copySheet(from, to int) {
  435. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  436. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  437. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  438. if len(worksheet.SheetViews.SheetView) > 0 {
  439. worksheet.SheetViews.SheetView[0].TabSelected = false
  440. }
  441. worksheet.Drawing = nil
  442. worksheet.TableParts = nil
  443. worksheet.PageSetUp = nil
  444. f.Sheet[path] = worksheet
  445. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  446. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  447. _, ok := f.XLSX[fromRels]
  448. if ok {
  449. f.XLSX[toRels] = f.XLSX[fromRels]
  450. }
  451. }
  452. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  453. // name. A workbook must contain at least one visible worksheet. If the given
  454. // worksheet has been activated, this setting will be invalidated. Sheet state
  455. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  456. //
  457. // visible
  458. // hidden
  459. // veryHidden
  460. //
  461. // For example, hide Sheet1:
  462. //
  463. // xlsx.SetSheetVisible("Sheet1", false)
  464. //
  465. func (f *File) SetSheetVisible(name string, visible bool) {
  466. name = trimSheetName(name)
  467. content := f.workbookReader()
  468. if visible {
  469. for k, v := range content.Sheets.Sheet {
  470. if v.Name == name {
  471. content.Sheets.Sheet[k].State = ""
  472. }
  473. }
  474. return
  475. }
  476. count := 0
  477. for _, v := range content.Sheets.Sheet {
  478. if v.State != "hidden" {
  479. count++
  480. }
  481. }
  482. for k, v := range content.Sheets.Sheet {
  483. xlsx := f.workSheetReader(f.GetSheetMap()[k])
  484. tabSelected := false
  485. if len(xlsx.SheetViews.SheetView) > 0 {
  486. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  487. }
  488. if v.Name == name && count > 1 && !tabSelected {
  489. content.Sheets.Sheet[k].State = "hidden"
  490. }
  491. }
  492. }
  493. // parseFormatPanesSet provides a function to parse the panes settings.
  494. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  495. format := formatPanes{}
  496. err := json.Unmarshal([]byte(formatSet), &format)
  497. return &format, err
  498. }
  499. // SetPanes provides a function to create and remove freeze panes and split panes
  500. // by given worksheet name and panes format set.
  501. //
  502. // activePane defines the pane that is active. The possible values for this
  503. // attribute are defined in the following table:
  504. //
  505. // Enumeration Value | Description
  506. // --------------------------------+-------------------------------------------------------------
  507. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  508. // | splits are applied.
  509. // |
  510. // | This value is also used when only a horizontal split has
  511. // | been applied, dividing the pane into upper and lower
  512. // | regions. In that case, this value specifies the bottom
  513. // | pane.
  514. // |
  515. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  516. // | splits are applied.
  517. // |
  518. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  519. // | are applied.
  520. // |
  521. // | This value is also used when only a horizontal split has
  522. // | been applied, dividing the pane into upper and lower
  523. // | regions. In that case, this value specifies the top pane.
  524. // |
  525. // | This value is also used when only a vertical split has
  526. // | been applied, dividing the pane into right and left
  527. // | regions. In that case, this value specifies the left pane
  528. // |
  529. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  530. // | splits are applied.
  531. // |
  532. // | This value is also used when only a vertical split has
  533. // | been applied, dividing the pane into right and left
  534. // | regions. In that case, this value specifies the right
  535. // | pane.
  536. //
  537. // Pane state type is restricted to the values supported currently listed in the following table:
  538. //
  539. // Enumeration Value | Description
  540. // --------------------------------+-------------------------------------------------------------
  541. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  542. // | this state, when the panes are unfrozen again, a single
  543. // | pane results, with no split.
  544. // |
  545. // | In this state, the split bars are not adjustable.
  546. // |
  547. // split (Split) | Panes are split, but not frozen. In this state, the split
  548. // | bars are adjustable by the user.
  549. //
  550. // x_split (Horizontal Split Position): Horizontal position of the split, in
  551. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  552. // indicates the number of columns visible in the top pane.
  553. //
  554. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  555. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  556. // number of rows visible in the left pane. The possible values for this
  557. // attribute are defined by the W3C XML Schema double datatype.
  558. //
  559. // top_left_cell: Location of the top left visible cell in the bottom right pane
  560. // (when in Left-To-Right mode).
  561. //
  562. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  563. // set of ranges.
  564. //
  565. // An example of how to freeze column A in the Sheet1 and set the active cell on
  566. // Sheet1!K16:
  567. //
  568. // 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"}]}`)
  569. //
  570. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  571. // ranges on Sheet1!A11:XFD11:
  572. //
  573. // 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"}]}`)
  574. //
  575. // An example of how to create split panes in the Sheet1 and set the active cell
  576. // on Sheet1!J60:
  577. //
  578. // 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"}]}`)
  579. //
  580. // An example of how to unfreeze and remove all panes on Sheet1:
  581. //
  582. // xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  583. //
  584. func (f *File) SetPanes(sheet, panes string) {
  585. fs, _ := parseFormatPanesSet(panes)
  586. xlsx := f.workSheetReader(sheet)
  587. p := &xlsxPane{
  588. ActivePane: fs.ActivePane,
  589. TopLeftCell: fs.TopLeftCell,
  590. XSplit: float64(fs.XSplit),
  591. YSplit: float64(fs.YSplit),
  592. }
  593. if fs.Freeze {
  594. p.State = "frozen"
  595. }
  596. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  597. if !(fs.Freeze) && !(fs.Split) {
  598. if len(xlsx.SheetViews.SheetView) > 0 {
  599. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  600. }
  601. }
  602. s := []*xlsxSelection{}
  603. for _, p := range fs.Panes {
  604. s = append(s, &xlsxSelection{
  605. ActiveCell: p.ActiveCell,
  606. Pane: p.Pane,
  607. SQRef: p.SQRef,
  608. })
  609. }
  610. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  611. }
  612. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  613. // name. For example, get visible state of Sheet1:
  614. //
  615. // xlsx.GetSheetVisible("Sheet1")
  616. //
  617. func (f *File) GetSheetVisible(name string) bool {
  618. content := f.workbookReader()
  619. visible := false
  620. for k, v := range content.Sheets.Sheet {
  621. if v.Name == trimSheetName(name) {
  622. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  623. visible = true
  624. }
  625. }
  626. }
  627. return visible
  628. }
  629. // SearchSheet provides a function to get coordinates by given worksheet name
  630. // and cell value. This function only supports exact match of strings and
  631. // numbers, doesn't support the calculated result, formatted numbers and
  632. // conditional lookup currently. If it is a merged cell, it will return the
  633. // coordinates of the upper left corner of the merged area. For example,
  634. // search the coordinates of the value of "100" on Sheet1:
  635. //
  636. // xlsx.SearchSheet("Sheet1", "100")
  637. //
  638. func (f *File) SearchSheet(sheet, value string) []string {
  639. xlsx := f.workSheetReader(sheet)
  640. result := []string{}
  641. name, ok := f.sheetMap[trimSheetName(sheet)]
  642. if !ok {
  643. return result
  644. }
  645. if xlsx != nil {
  646. output, _ := xml.Marshal(f.Sheet[name])
  647. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  648. }
  649. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  650. d := f.sharedStringsReader()
  651. var inElement string
  652. var r xlsxRow
  653. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  654. for {
  655. token, _ := decoder.Token()
  656. if token == nil {
  657. break
  658. }
  659. switch startElement := token.(type) {
  660. case xml.StartElement:
  661. inElement = startElement.Name.Local
  662. if inElement == "row" {
  663. r = xlsxRow{}
  664. _ = decoder.DecodeElement(&r, &startElement)
  665. for _, colCell := range r.C {
  666. val, _ := colCell.getValueFrom(f, d)
  667. if val != value {
  668. continue
  669. }
  670. result = append(result, fmt.Sprintf("%s%d", strings.Map(letterOnlyMapF, colCell.R), r.R))
  671. }
  672. }
  673. default:
  674. }
  675. }
  676. return result
  677. }
  678. // ProtectSheet provides a function to prevent other users from accidentally
  679. // or deliberately changing, moving, or deleting data in a worksheet. For
  680. // example, protect Sheet1 with protection settings:
  681. //
  682. // xlsx.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  683. // Password: "password",
  684. // EditScenarios: false,
  685. // })
  686. //
  687. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) {
  688. xlsx := f.workSheetReader(sheet)
  689. if settings == nil {
  690. settings = &FormatSheetProtection{
  691. EditObjects: true,
  692. EditScenarios: true,
  693. SelectLockedCells: true,
  694. }
  695. }
  696. xlsx.SheetProtection = &xlsxSheetProtection{
  697. AutoFilter: settings.AutoFilter,
  698. DeleteColumns: settings.DeleteColumns,
  699. DeleteRows: settings.DeleteRows,
  700. FormatCells: settings.FormatCells,
  701. FormatColumns: settings.FormatColumns,
  702. FormatRows: settings.FormatRows,
  703. InsertColumns: settings.InsertColumns,
  704. InsertHyperlinks: settings.InsertHyperlinks,
  705. InsertRows: settings.InsertRows,
  706. Objects: settings.EditObjects,
  707. PivotTables: settings.PivotTables,
  708. Scenarios: settings.EditScenarios,
  709. SelectLockedCells: settings.SelectLockedCells,
  710. SelectUnlockedCells: settings.SelectUnlockedCells,
  711. Sheet: true,
  712. Sort: settings.Sort,
  713. }
  714. if settings.Password != "" {
  715. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  716. }
  717. }
  718. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  719. func (f *File) UnprotectSheet(sheet string) {
  720. xlsx := f.workSheetReader(sheet)
  721. xlsx.SheetProtection = nil
  722. }
  723. // trimSheetName provides a function to trim invaild characters by given worksheet
  724. // name.
  725. func trimSheetName(name string) string {
  726. r := []rune{}
  727. for _, v := range name {
  728. switch v {
  729. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  730. continue
  731. default:
  732. r = append(r, v)
  733. }
  734. }
  735. name = string(r)
  736. if utf8.RuneCountInString(name) > 31 {
  737. name = string([]rune(name)[0:31])
  738. }
  739. return name
  740. }