sheet.go 27 KB

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