sheet.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. "io/ioutil"
  16. "os"
  17. "path"
  18. "regexp"
  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.DeleteSheet(name)
  33. f.SheetCount++
  34. wb := f.workbookReader()
  35. sheetID := 0
  36. for _, v := range wb.Sheets.Sheet {
  37. if v.SheetID > sheetID {
  38. sheetID = v.SheetID
  39. }
  40. }
  41. sheetID++
  42. // Update docProps/app.xml
  43. f.setAppXML()
  44. // Update [Content_Types].xml
  45. f.setContentTypes(sheetID)
  46. // Create new sheet /xl/worksheets/sheet%d.xml
  47. f.setSheet(sheetID, name)
  48. // Update xl/_rels/workbook.xml.rels
  49. rID := f.addXlsxWorkbookRels(sheetID)
  50. // Update xl/workbook.xml
  51. f.setWorkbook(name, sheetID, rID)
  52. return sheetID
  53. }
  54. // contentTypesReader provides a function to get the pointer to the
  55. // [Content_Types].xml structure after deserialization.
  56. func (f *File) contentTypesReader() *xlsxTypes {
  57. if f.ContentTypes == nil {
  58. var content xlsxTypes
  59. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("[Content_Types].xml")), &content)
  60. f.ContentTypes = &content
  61. }
  62. return f.ContentTypes
  63. }
  64. // contentTypesWriter provides a function to save [Content_Types].xml after
  65. // serialize structure.
  66. func (f *File) contentTypesWriter() {
  67. if f.ContentTypes != nil {
  68. output, _ := xml.Marshal(f.ContentTypes)
  69. f.saveFileList("[Content_Types].xml", output)
  70. }
  71. }
  72. // workbookReader provides a function to get the pointer to the xl/workbook.xml
  73. // structure after deserialization.
  74. func (f *File) workbookReader() *xlsxWorkbook {
  75. if f.WorkBook == nil {
  76. var content xlsxWorkbook
  77. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/workbook.xml")), &content)
  78. f.WorkBook = &content
  79. }
  80. return f.WorkBook
  81. }
  82. // workBookWriter provides a function to save xl/workbook.xml after serialize
  83. // structure.
  84. func (f *File) workBookWriter() {
  85. if f.WorkBook != nil {
  86. output, _ := xml.Marshal(f.WorkBook)
  87. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpaceBytes(output))
  88. }
  89. }
  90. // workSheetWriter provides a function to save xl/worksheets/sheet%d.xml after
  91. // serialize structure.
  92. func (f *File) workSheetWriter() {
  93. for p, sheet := range f.Sheet {
  94. if sheet != nil {
  95. for k, v := range sheet.SheetData.Row {
  96. f.Sheet[p].SheetData.Row[k].C = trimCell(v.C)
  97. }
  98. output, _ := xml.Marshal(sheet)
  99. f.saveFileList(p, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  100. ok := f.checked[p]
  101. if ok {
  102. f.checked[p] = false
  103. }
  104. }
  105. }
  106. }
  107. // trimCell provides a function to trim blank cells which created by completeCol.
  108. func trimCell(column []xlsxC) []xlsxC {
  109. col := make([]xlsxC, len(column))
  110. i := 0
  111. for _, c := range column {
  112. if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
  113. col[i] = c
  114. i++
  115. }
  116. }
  117. return col[0:i]
  118. }
  119. // setContentTypes provides a function to read and update property of contents
  120. // type of XLSX.
  121. func (f *File) setContentTypes(index int) {
  122. content := f.contentTypesReader()
  123. content.Overrides = append(content.Overrides, xlsxOverride{
  124. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  125. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  126. })
  127. }
  128. // setSheet provides a function to update sheet property by given index.
  129. func (f *File) setSheet(index int, name string) {
  130. var xlsx xlsxWorksheet
  131. xlsx.Dimension.Ref = "A1"
  132. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  133. WorkbookViewID: 0,
  134. })
  135. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  136. f.sheetMap[trimSheetName(name)] = path
  137. f.Sheet[path] = &xlsx
  138. }
  139. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  140. // allowed in sheet title.
  141. func (f *File) setWorkbook(name string, sheetID, rid int) {
  142. content := f.workbookReader()
  143. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  144. Name: trimSheetName(name),
  145. SheetID: sheetID,
  146. ID: "rId" + strconv.Itoa(rid),
  147. })
  148. }
  149. // workbookRelsReader provides a function to read and unmarshal workbook
  150. // relationships of XLSX file.
  151. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  152. if f.WorkBookRels == nil {
  153. var content xlsxWorkbookRels
  154. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  155. f.WorkBookRels = &content
  156. }
  157. return f.WorkBookRels
  158. }
  159. // workBookRelsWriter provides a function to save xl/_rels/workbook.xml.rels after
  160. // serialize structure.
  161. func (f *File) workBookRelsWriter() {
  162. if f.WorkBookRels != nil {
  163. output, _ := xml.Marshal(f.WorkBookRels)
  164. f.saveFileList("xl/_rels/workbook.xml.rels", output)
  165. }
  166. }
  167. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  168. func (f *File) addXlsxWorkbookRels(sheet int) int {
  169. content := f.workbookRelsReader()
  170. rID := 0
  171. for _, v := range content.Relationships {
  172. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  173. if t > rID {
  174. rID = t
  175. }
  176. }
  177. rID++
  178. ID := bytes.Buffer{}
  179. ID.WriteString("rId")
  180. ID.WriteString(strconv.Itoa(rID))
  181. target := bytes.Buffer{}
  182. target.WriteString("worksheets/sheet")
  183. target.WriteString(strconv.Itoa(sheet))
  184. target.WriteString(".xml")
  185. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  186. ID: ID.String(),
  187. Target: target.String(),
  188. Type: SourceRelationshipWorkSheet,
  189. })
  190. return rID
  191. }
  192. // setAppXML update docProps/app.xml file of XML.
  193. func (f *File) setAppXML() {
  194. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  195. }
  196. // replaceRelationshipsNameSpaceBytes; Some tools that read XLSX files have
  197. // very strict requirements about the structure of the input XML. In
  198. // particular both Numbers on the Mac and SAS dislike inline XML namespace
  199. // declarations, or namespace prefixes that don't match the ones that Excel
  200. // itself uses. This is a problem because the Go XML library doesn't multiple
  201. // namespace declarations in a single element of a document. This function is
  202. // a horrible hack to fix that after the XML marshalling is completed.
  203. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  204. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  205. 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">`)
  206. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  207. }
  208. // SetActiveSheet provides function to set default active worksheet of XLSX by
  209. // given index. Note that active index is different from the index returned by
  210. // function GetSheetMap(). It should be greater than 0 and less than total
  211. // worksheet numbers.
  212. func (f *File) SetActiveSheet(index int) {
  213. if index < 1 {
  214. index = 1
  215. }
  216. wb := f.workbookReader()
  217. for activeTab, sheet := range wb.Sheets.Sheet {
  218. if sheet.SheetID == index {
  219. if len(wb.BookViews.WorkBookView) > 0 {
  220. wb.BookViews.WorkBookView[0].ActiveTab = activeTab
  221. } else {
  222. wb.BookViews.WorkBookView = append(wb.BookViews.WorkBookView, xlsxWorkBookView{
  223. ActiveTab: activeTab,
  224. })
  225. }
  226. }
  227. }
  228. for idx, name := range f.GetSheetMap() {
  229. xlsx := f.workSheetReader(name)
  230. if len(xlsx.SheetViews.SheetView) > 0 {
  231. xlsx.SheetViews.SheetView[0].TabSelected = false
  232. }
  233. if index == idx {
  234. if len(xlsx.SheetViews.SheetView) > 0 {
  235. xlsx.SheetViews.SheetView[0].TabSelected = true
  236. } else {
  237. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  238. TabSelected: true,
  239. })
  240. }
  241. }
  242. }
  243. }
  244. // GetActiveSheetIndex provides a function to get active sheet index of the
  245. // XLSX. If not found the active sheet will be return integer 0.
  246. func (f *File) GetActiveSheetIndex() int {
  247. for idx, name := range f.GetSheetMap() {
  248. xlsx := f.workSheetReader(name)
  249. for _, sheetView := range xlsx.SheetViews.SheetView {
  250. if sheetView.TabSelected {
  251. return idx
  252. }
  253. }
  254. }
  255. return 0
  256. }
  257. // SetSheetName provides a function to set the worksheet name be given old and
  258. // new worksheet name. Maximum 31 characters are allowed in sheet title and
  259. // this function only changes the name of the sheet and will not update the
  260. // sheet name in the formula or reference associated with the cell. So there
  261. // may be problem formula error or reference missing.
  262. func (f *File) SetSheetName(oldName, newName string) {
  263. oldName = trimSheetName(oldName)
  264. newName = trimSheetName(newName)
  265. content := f.workbookReader()
  266. for k, v := range content.Sheets.Sheet {
  267. if v.Name == oldName {
  268. content.Sheets.Sheet[k].Name = newName
  269. f.sheetMap[newName] = f.sheetMap[oldName]
  270. delete(f.sheetMap, oldName)
  271. }
  272. }
  273. }
  274. // GetSheetName provides a function to get worksheet name of XLSX by given
  275. // worksheet index. If given sheet index is invalid, will return an empty
  276. // string.
  277. func (f *File) GetSheetName(index int) string {
  278. content := f.workbookReader()
  279. rels := f.workbookRelsReader()
  280. for _, rel := range rels.Relationships {
  281. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  282. if rID == index {
  283. for _, v := range content.Sheets.Sheet {
  284. if v.ID == rel.ID {
  285. return v.Name
  286. }
  287. }
  288. }
  289. }
  290. return ""
  291. }
  292. // GetSheetIndex provides a function to get worksheet index of XLSX by given sheet
  293. // name. If given worksheet name is invalid, will return an integer type value
  294. // 0.
  295. func (f *File) GetSheetIndex(name string) int {
  296. content := f.workbookReader()
  297. rels := f.workbookRelsReader()
  298. for _, v := range content.Sheets.Sheet {
  299. if v.Name == name {
  300. for _, rel := range rels.Relationships {
  301. if v.ID == rel.ID {
  302. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  303. return rID
  304. }
  305. }
  306. }
  307. }
  308. return 0
  309. }
  310. // GetSheetMap provides a function to get worksheet name and index map of XLSX.
  311. // For example:
  312. //
  313. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  314. // if err != nil {
  315. // return
  316. // }
  317. // for index, name := range xlsx.GetSheetMap() {
  318. // fmt.Println(index, name)
  319. // }
  320. //
  321. func (f *File) GetSheetMap() map[int]string {
  322. content := f.workbookReader()
  323. rels := f.workbookRelsReader()
  324. sheetMap := map[int]string{}
  325. for _, v := range content.Sheets.Sheet {
  326. for _, rel := range rels.Relationships {
  327. relStr := strings.SplitN(rel.Target, "worksheets/sheet", 2)
  328. if rel.ID == v.ID && len(relStr) == 2 {
  329. rID, _ := strconv.Atoi(strings.TrimSuffix(relStr[1], ".xml"))
  330. sheetMap[rID] = v.Name
  331. }
  332. }
  333. }
  334. return sheetMap
  335. }
  336. // getSheetMap provides a function to get worksheet name and XML file path map of
  337. // XLSX.
  338. func (f *File) getSheetMap() map[string]string {
  339. maps := make(map[string]string)
  340. for idx, name := range f.GetSheetMap() {
  341. maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
  342. }
  343. return maps
  344. }
  345. // SetSheetBackground provides a function to set background picture by given
  346. // worksheet name and file path.
  347. func (f *File) SetSheetBackground(sheet, picture string) error {
  348. var err error
  349. // Check picture exists first.
  350. if _, err = os.Stat(picture); os.IsNotExist(err) {
  351. return err
  352. }
  353. ext, ok := supportImageTypes[path.Ext(picture)]
  354. if !ok {
  355. return errors.New("unsupported image extension")
  356. }
  357. pictureID := f.countMedia() + 1
  358. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  359. f.addSheetPicture(sheet, rID)
  360. file, _ := ioutil.ReadFile(picture)
  361. f.addMedia(file, ext)
  362. f.setContentTypePartImageExtensions()
  363. return err
  364. }
  365. // DeleteSheet provides a function to delete worksheet in a workbook by given
  366. // worksheet name. Use this method with caution, which will affect changes in
  367. // references such as formulas, charts, and so on. If there is any referenced
  368. // value of the deleted worksheet, it will cause a file error when you open it.
  369. // This function will be invalid when only the one worksheet is left.
  370. func (f *File) DeleteSheet(name string) {
  371. content := f.workbookReader()
  372. for k, v := range content.Sheets.Sheet {
  373. if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
  374. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  375. sheet := "xl/worksheets/sheet" + strconv.Itoa(v.SheetID) + ".xml"
  376. rels := "xl/worksheets/_rels/sheet" + strconv.Itoa(v.SheetID) + ".xml.rels"
  377. target := f.deleteSheetFromWorkbookRels(v.ID)
  378. f.deleteSheetFromContentTypes(target)
  379. delete(f.sheetMap, name)
  380. delete(f.XLSX, sheet)
  381. delete(f.XLSX, rels)
  382. delete(f.Sheet, sheet)
  383. f.SheetCount--
  384. }
  385. }
  386. f.SetActiveSheet(len(f.GetSheetMap()))
  387. }
  388. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  389. // relationships by given relationships ID in the file
  390. // xl/_rels/workbook.xml.rels.
  391. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  392. content := f.workbookRelsReader()
  393. for k, v := range content.Relationships {
  394. if v.ID == rID {
  395. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  396. return v.Target
  397. }
  398. }
  399. return ""
  400. }
  401. // deleteSheetFromContentTypes provides a function to remove worksheet
  402. // relationships by given target name in the file [Content_Types].xml.
  403. func (f *File) deleteSheetFromContentTypes(target string) {
  404. content := f.contentTypesReader()
  405. for k, v := range content.Overrides {
  406. if v.PartName == "/xl/"+target {
  407. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  408. }
  409. }
  410. }
  411. // CopySheet provides a function to duplicate a worksheet by gave source and
  412. // target worksheet index. Note that currently doesn't support duplicate
  413. // workbooks that contain tables, charts or pictures. For Example:
  414. //
  415. // // Sheet1 already exists...
  416. // index := xlsx.NewSheet("Sheet2")
  417. // err := xlsx.CopySheet(1, index)
  418. // return err
  419. //
  420. func (f *File) CopySheet(from, to int) error {
  421. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  422. return errors.New("invalid worksheet index")
  423. }
  424. f.copySheet(from, to)
  425. return nil
  426. }
  427. // copySheet provides a function to duplicate a worksheet by gave source and
  428. // target worksheet name.
  429. func (f *File) copySheet(from, to int) {
  430. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  431. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  432. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  433. if len(worksheet.SheetViews.SheetView) > 0 {
  434. worksheet.SheetViews.SheetView[0].TabSelected = false
  435. }
  436. worksheet.Drawing = nil
  437. worksheet.TableParts = nil
  438. worksheet.PageSetUp = nil
  439. f.Sheet[path] = worksheet
  440. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  441. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  442. _, ok := f.XLSX[fromRels]
  443. if ok {
  444. f.XLSX[toRels] = f.XLSX[fromRels]
  445. }
  446. }
  447. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  448. // name. A workbook must contain at least one visible worksheet. If the given
  449. // worksheet has been activated, this setting will be invalidated. Sheet state
  450. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  451. //
  452. // visible
  453. // hidden
  454. // veryHidden
  455. //
  456. // For example, hide Sheet1:
  457. //
  458. // xlsx.SetSheetVisible("Sheet1", false)
  459. //
  460. func (f *File) SetSheetVisible(name string, visible bool) {
  461. name = trimSheetName(name)
  462. content := f.workbookReader()
  463. if visible {
  464. for k, v := range content.Sheets.Sheet {
  465. if v.Name == name {
  466. content.Sheets.Sheet[k].State = ""
  467. }
  468. }
  469. return
  470. }
  471. count := 0
  472. for _, v := range content.Sheets.Sheet {
  473. if v.State != "hidden" {
  474. count++
  475. }
  476. }
  477. for k, v := range content.Sheets.Sheet {
  478. xlsx := f.workSheetReader(f.GetSheetMap()[k])
  479. tabSelected := false
  480. if len(xlsx.SheetViews.SheetView) > 0 {
  481. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  482. }
  483. if v.Name == name && count > 1 && !tabSelected {
  484. content.Sheets.Sheet[k].State = "hidden"
  485. }
  486. }
  487. }
  488. // parseFormatPanesSet provides a function to parse the panes settings.
  489. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  490. format := formatPanes{}
  491. err := json.Unmarshal([]byte(formatSet), &format)
  492. return &format, err
  493. }
  494. // SetPanes provides a function to create and remove freeze panes and split panes
  495. // by given worksheet name and panes format set.
  496. //
  497. // activePane defines the pane that is active. The possible values for this
  498. // attribute are defined in the following table:
  499. //
  500. // Enumeration Value | Description
  501. // --------------------------------+-------------------------------------------------------------
  502. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  503. // | splits are applied.
  504. // |
  505. // | This value is also used when only a horizontal split has
  506. // | been applied, dividing the pane into upper and lower
  507. // | regions. In that case, this value specifies the bottom
  508. // | pane.
  509. // |
  510. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  511. // | splits are applied.
  512. // |
  513. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  514. // | are applied.
  515. // |
  516. // | This value is also used when only a horizontal split has
  517. // | been applied, dividing the pane into upper and lower
  518. // | regions. In that case, this value specifies the top pane.
  519. // |
  520. // | This value is also used when only a vertical split has
  521. // | been applied, dividing the pane into right and left
  522. // | regions. In that case, this value specifies the left pane
  523. // |
  524. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  525. // | splits are applied.
  526. // |
  527. // | This value is also used when only a vertical split has
  528. // | been applied, dividing the pane into right and left
  529. // | regions. In that case, this value specifies the right
  530. // | pane.
  531. //
  532. // Pane state type is restricted to the values supported currently listed in the following table:
  533. //
  534. // Enumeration Value | Description
  535. // --------------------------------+-------------------------------------------------------------
  536. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  537. // | this state, when the panes are unfrozen again, a single
  538. // | pane results, with no split.
  539. // |
  540. // | In this state, the split bars are not adjustable.
  541. // |
  542. // split (Split) | Panes are split, but not frozen. In this state, the split
  543. // | bars are adjustable by the user.
  544. //
  545. // x_split (Horizontal Split Position): Horizontal position of the split, in
  546. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  547. // indicates the number of columns visible in the top pane.
  548. //
  549. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  550. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  551. // number of rows visible in the left pane. The possible values for this
  552. // attribute are defined by the W3C XML Schema double datatype.
  553. //
  554. // top_left_cell: Location of the top left visible cell in the bottom right pane
  555. // (when in Left-To-Right mode).
  556. //
  557. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  558. // set of ranges.
  559. //
  560. // An example of how to freeze column A in the Sheet1 and set the active cell on
  561. // Sheet1!K16:
  562. //
  563. // 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"}]}`)
  564. //
  565. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  566. // ranges on Sheet1!A11:XFD11:
  567. //
  568. // 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"}]}`)
  569. //
  570. // An example of how to create split panes in the Sheet1 and set the active cell
  571. // on Sheet1!J60:
  572. //
  573. // 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"}]}`)
  574. //
  575. // An example of how to unfreeze and remove all panes on Sheet1:
  576. //
  577. // xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  578. //
  579. func (f *File) SetPanes(sheet, panes string) {
  580. fs, _ := parseFormatPanesSet(panes)
  581. xlsx := f.workSheetReader(sheet)
  582. p := &xlsxPane{
  583. ActivePane: fs.ActivePane,
  584. TopLeftCell: fs.TopLeftCell,
  585. XSplit: float64(fs.XSplit),
  586. YSplit: float64(fs.YSplit),
  587. }
  588. if fs.Freeze {
  589. p.State = "frozen"
  590. }
  591. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  592. if !(fs.Freeze) && !(fs.Split) {
  593. if len(xlsx.SheetViews.SheetView) > 0 {
  594. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  595. }
  596. }
  597. s := []*xlsxSelection{}
  598. for _, p := range fs.Panes {
  599. s = append(s, &xlsxSelection{
  600. ActiveCell: p.ActiveCell,
  601. Pane: p.Pane,
  602. SQRef: p.SQRef,
  603. })
  604. }
  605. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  606. }
  607. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  608. // name. For example, get visible state of Sheet1:
  609. //
  610. // xlsx.GetSheetVisible("Sheet1")
  611. //
  612. func (f *File) GetSheetVisible(name string) bool {
  613. content := f.workbookReader()
  614. visible := false
  615. for k, v := range content.Sheets.Sheet {
  616. if v.Name == trimSheetName(name) {
  617. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  618. visible = true
  619. }
  620. }
  621. }
  622. return visible
  623. }
  624. // SearchSheet provides a function to get coordinates by given worksheet name,
  625. // cell value, and regular expression. The function doesn't support searching
  626. // on the calculated result, formatted numbers and conditional lookup
  627. // currently. If it is a merged cell, it will return the coordinates of the
  628. // upper left corner of the merged area.
  629. //
  630. // An example of search the coordinates of the value of "100" on Sheet1:
  631. //
  632. // result, err := xlsx.SearchSheet("Sheet1", "100")
  633. //
  634. // An example of search the coordinates where the numerical value in the range
  635. // of "0-9" of Sheet1 is described:
  636. //
  637. // result, err := xlsx.SearchSheet("Sheet1", "[0-9]", true)
  638. //
  639. func (f *File) SearchSheet(sheet, value string, reg ...bool) ([]string, error) {
  640. var regSearch bool
  641. for _, r := range reg {
  642. regSearch = r
  643. }
  644. xlsx := f.workSheetReader(sheet)
  645. var (
  646. result []string
  647. )
  648. name, ok := f.sheetMap[trimSheetName(sheet)]
  649. if !ok {
  650. return result, nil
  651. }
  652. if xlsx != nil {
  653. output, _ := xml.Marshal(f.Sheet[name])
  654. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  655. }
  656. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  657. d := f.sharedStringsReader()
  658. var inElement string
  659. var r xlsxRow
  660. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  661. for {
  662. token, _ := decoder.Token()
  663. if token == nil {
  664. break
  665. }
  666. switch startElement := token.(type) {
  667. case xml.StartElement:
  668. inElement = startElement.Name.Local
  669. if inElement == "row" {
  670. r = xlsxRow{}
  671. _ = decoder.DecodeElement(&r, &startElement)
  672. for _, colCell := range r.C {
  673. val, _ := colCell.getValueFrom(f, d)
  674. if regSearch {
  675. regex := regexp.MustCompile(value)
  676. if !regex.MatchString(val) {
  677. continue
  678. }
  679. } else {
  680. if val != value {
  681. continue
  682. }
  683. }
  684. cellCol, _, err := CellNameToCoordinates(colCell.R)
  685. if err != nil {
  686. return result, err
  687. }
  688. cellName, err := CoordinatesToCellName(cellCol, r.R)
  689. if err != nil {
  690. return result, err
  691. }
  692. result = append(result, cellName)
  693. }
  694. }
  695. default:
  696. }
  697. }
  698. return result, nil
  699. }
  700. // ProtectSheet provides a function to prevent other users from accidentally
  701. // or deliberately changing, moving, or deleting data in a worksheet. For
  702. // example, protect Sheet1 with protection settings:
  703. //
  704. // xlsx.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  705. // Password: "password",
  706. // EditScenarios: false,
  707. // })
  708. //
  709. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) {
  710. xlsx := f.workSheetReader(sheet)
  711. if settings == nil {
  712. settings = &FormatSheetProtection{
  713. EditObjects: true,
  714. EditScenarios: true,
  715. SelectLockedCells: true,
  716. }
  717. }
  718. xlsx.SheetProtection = &xlsxSheetProtection{
  719. AutoFilter: settings.AutoFilter,
  720. DeleteColumns: settings.DeleteColumns,
  721. DeleteRows: settings.DeleteRows,
  722. FormatCells: settings.FormatCells,
  723. FormatColumns: settings.FormatColumns,
  724. FormatRows: settings.FormatRows,
  725. InsertColumns: settings.InsertColumns,
  726. InsertHyperlinks: settings.InsertHyperlinks,
  727. InsertRows: settings.InsertRows,
  728. Objects: settings.EditObjects,
  729. PivotTables: settings.PivotTables,
  730. Scenarios: settings.EditScenarios,
  731. SelectLockedCells: settings.SelectLockedCells,
  732. SelectUnlockedCells: settings.SelectUnlockedCells,
  733. Sheet: true,
  734. Sort: settings.Sort,
  735. }
  736. if settings.Password != "" {
  737. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  738. }
  739. }
  740. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  741. func (f *File) UnprotectSheet(sheet string) {
  742. xlsx := f.workSheetReader(sheet)
  743. xlsx.SheetProtection = nil
  744. }
  745. // trimSheetName provides a function to trim invaild characters by given worksheet
  746. // name.
  747. func trimSheetName(name string) string {
  748. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  749. r := make([]rune, 0, 31)
  750. for _, v := range name {
  751. switch v {
  752. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  753. continue
  754. default:
  755. r = append(r, v)
  756. }
  757. if len(r) == 31 {
  758. break
  759. }
  760. }
  761. name = string(r)
  762. }
  763. return name
  764. }
  765. // PageLayoutOption is an option of a page layout of a worksheet. See
  766. // SetPageLayout().
  767. type PageLayoutOption interface {
  768. setPageLayout(layout *xlsxPageSetUp)
  769. }
  770. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  771. type PageLayoutOptionPtr interface {
  772. PageLayoutOption
  773. getPageLayout(layout *xlsxPageSetUp)
  774. }
  775. type (
  776. // PageLayoutOrientation defines the orientation of page layout for a
  777. // worksheet.
  778. PageLayoutOrientation string
  779. // PageLayoutPaperSize defines the paper size of the worksheet
  780. PageLayoutPaperSize int
  781. )
  782. const (
  783. // OrientationPortrait indicates page layout orientation id portrait.
  784. OrientationPortrait = "portrait"
  785. // OrientationLandscape indicates page layout orientation id landscape.
  786. OrientationLandscape = "landscape"
  787. )
  788. // setPageLayout provides a method to set the orientation for the worksheet.
  789. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  790. ps.Orientation = string(o)
  791. }
  792. // getPageLayout provides a method to get the orientation for the worksheet.
  793. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  794. // Excel default: portrait
  795. if ps == nil || ps.Orientation == "" {
  796. *o = OrientationPortrait
  797. return
  798. }
  799. *o = PageLayoutOrientation(ps.Orientation)
  800. }
  801. // setPageLayout provides a method to set the paper size for the worksheet.
  802. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  803. ps.PaperSize = int(p)
  804. }
  805. // getPageLayout provides a method to get the paper size for the worksheet.
  806. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  807. // Excel default: 1
  808. if ps == nil || ps.PaperSize == 0 {
  809. *p = 1
  810. return
  811. }
  812. *p = PageLayoutPaperSize(ps.PaperSize)
  813. }
  814. // SetPageLayout provides a function to sets worksheet page layout.
  815. //
  816. // Available options:
  817. // PageLayoutOrientation(string)
  818. // PageLayoutPaperSize(int)
  819. //
  820. // The following shows the paper size sorted by excelize index number:
  821. //
  822. // Index | Paper Size
  823. // -------+-----------------------------------------------
  824. // 1 | Letter paper (8.5 in. by 11 in.)
  825. // 2 | Letter small paper (8.5 in. by 11 in.)
  826. // 3 | Tabloid paper (11 in. by 17 in.)
  827. // 4 | Ledger paper (17 in. by 11 in.)
  828. // 5 | Legal paper (8.5 in. by 14 in.)
  829. // 6 | Statement paper (5.5 in. by 8.5 in.)
  830. // 7 | Executive paper (7.25 in. by 10.5 in.)
  831. // 8 | A3 paper (297 mm by 420 mm)
  832. // 9 | A4 paper (210 mm by 297 mm)
  833. // 10 | A4 small paper (210 mm by 297 mm)
  834. // 11 | A5 paper (148 mm by 210 mm)
  835. // 12 | B4 paper (250 mm by 353 mm)
  836. // 13 | B5 paper (176 mm by 250 mm)
  837. // 14 | Folio paper (8.5 in. by 13 in.)
  838. // 15 | Quarto paper (215 mm by 275 mm)
  839. // 16 | Standard paper (10 in. by 14 in.)
  840. // 17 | Standard paper (11 in. by 17 in.)
  841. // 18 | Note paper (8.5 in. by 11 in.)
  842. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  843. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  844. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  845. // 22 | #12 envelope (4.75 in. by 11 in.)
  846. // 23 | #14 envelope (5 in. by 11.5 in.)
  847. // 24 | C paper (17 in. by 22 in.)
  848. // 25 | D paper (22 in. by 34 in.)
  849. // 26 | E paper (34 in. by 44 in.)
  850. // 27 | DL envelope (110 mm by 220 mm)
  851. // 28 | C5 envelope (162 mm by 229 mm)
  852. // 29 | C3 envelope (324 mm by 458 mm)
  853. // 30 | C4 envelope (229 mm by 324 mm)
  854. // 31 | C6 envelope (114 mm by 162 mm)
  855. // 32 | C65 envelope (114 mm by 229 mm)
  856. // 33 | B4 envelope (250 mm by 353 mm)
  857. // 34 | B5 envelope (176 mm by 250 mm)
  858. // 35 | B6 envelope (176 mm by 125 mm)
  859. // 36 | Italy envelope (110 mm by 230 mm)
  860. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  861. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  862. // 39 | US standard fanfold (14.875 in. by 11 in.)
  863. // 40 | German standard fanfold (8.5 in. by 12 in.)
  864. // 41 | German legal fanfold (8.5 in. by 13 in.)
  865. // 42 | ISO B4 (250 mm by 353 mm)
  866. // 43 | Japanese postcard (100 mm by 148 mm)
  867. // 44 | Standard paper (9 in. by 11 in.)
  868. // 45 | Standard paper (10 in. by 11 in.)
  869. // 46 | Standard paper (15 in. by 11 in.)
  870. // 47 | Invite envelope (220 mm by 220 mm)
  871. // 50 | Letter extra paper (9.275 in. by 12 in.)
  872. // 51 | Legal extra paper (9.275 in. by 15 in.)
  873. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  874. // 53 | A4 extra paper (236 mm by 322 mm)
  875. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  876. // 55 | A4 transverse paper (210 mm by 297 mm)
  877. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  878. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  879. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  880. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  881. // 60 | A4 plus paper (210 mm by 330 mm)
  882. // 61 | A5 transverse paper (148 mm by 210 mm)
  883. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  884. // 63 | A3 extra paper (322 mm by 445 mm)
  885. // 64 | A5 extra paper (174 mm by 235 mm)
  886. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  887. // 66 | A2 paper (420 mm by 594 mm)
  888. // 67 | A3 transverse paper (297 mm by 420 mm)
  889. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  890. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  891. // 70 | A6 (105 mm x 148 mm)
  892. // 71 | Japanese Envelope Kaku #2
  893. // 72 | Japanese Envelope Kaku #3
  894. // 73 | Japanese Envelope Chou #3
  895. // 74 | Japanese Envelope Chou #4
  896. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  897. // 76 | A3 Rotated (420 mm x 297 mm)
  898. // 77 | A4 Rotated (297 mm x 210 mm)
  899. // 78 | A5 Rotated (210 mm x 148 mm)
  900. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  901. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  902. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  903. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  904. // 83 | A6 Rotated (148 mm x 105 mm)
  905. // 84 | Japanese Envelope Kaku #2 Rotated
  906. // 85 | Japanese Envelope Kaku #3 Rotated
  907. // 86 | Japanese Envelope Chou #3 Rotated
  908. // 87 | Japanese Envelope Chou #4 Rotated
  909. // 88 | B6 (JIS) (128 mm x 182 mm)
  910. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  911. // 90 | (12 in x 11 in)
  912. // 91 | Japanese Envelope You #4
  913. // 92 | Japanese Envelope You #4 Rotated
  914. // 93 | PRC 16K (146 mm x 215 mm)
  915. // 94 | PRC 32K (97 mm x 151 mm)
  916. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  917. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  918. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  919. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  920. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  921. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  922. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  923. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  924. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  925. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  926. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  927. // 106 | PRC 16K Rotated
  928. // 107 | PRC 32K Rotated
  929. // 108 | PRC 32K(Big) Rotated
  930. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  931. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  932. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  933. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  934. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  935. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  936. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  937. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  938. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  939. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  940. //
  941. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  942. s := f.workSheetReader(sheet)
  943. ps := s.PageSetUp
  944. if ps == nil {
  945. ps = new(xlsxPageSetUp)
  946. s.PageSetUp = ps
  947. }
  948. for _, opt := range opts {
  949. opt.setPageLayout(ps)
  950. }
  951. return nil
  952. }
  953. // GetPageLayout provides a function to gets worksheet page layout.
  954. //
  955. // Available options:
  956. // PageLayoutOrientation(string)
  957. // PageLayoutPaperSize(int)
  958. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  959. s := f.workSheetReader(sheet)
  960. ps := s.PageSetUp
  961. for _, opt := range opts {
  962. opt.getPageLayout(ps)
  963. }
  964. return nil
  965. }
  966. // workSheetRelsReader provides a function to get the pointer to the structure
  967. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  968. func (f *File) workSheetRelsReader(path string) *xlsxWorkbookRels {
  969. if f.WorkSheetRels[path] == nil {
  970. _, ok := f.XLSX[path]
  971. if ok {
  972. c := xlsxWorkbookRels{}
  973. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &c)
  974. f.WorkSheetRels[path] = &c
  975. }
  976. }
  977. return f.WorkSheetRels[path]
  978. }
  979. // workSheetRelsWriter provides a function to save
  980. // xl/worksheets/_rels/sheet%d.xml.rels after serialize structure.
  981. func (f *File) workSheetRelsWriter() {
  982. for p, r := range f.WorkSheetRels {
  983. if r != nil {
  984. v, _ := xml.Marshal(r)
  985. f.saveFileList(p, v)
  986. }
  987. }
  988. }
  989. // fillSheetData fill missing row and cell XML data to made it continuous from
  990. // first cell [1, 1] to last cell [col, row]
  991. func prepareSheetXML(xlsx *xlsxWorksheet, col int, row int) {
  992. rowCount := len(xlsx.SheetData.Row)
  993. if rowCount < row {
  994. // append missing rows
  995. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  996. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{R: rowIdx + 1})
  997. }
  998. }
  999. for rowIdx := range xlsx.SheetData.Row {
  1000. rowData := &xlsx.SheetData.Row[rowIdx] // take reference
  1001. cellCount := len(rowData.C)
  1002. if cellCount < col {
  1003. for colIdx := cellCount; colIdx < col; colIdx++ {
  1004. cellName, _ := CoordinatesToCellName(colIdx+1, rowIdx+1)
  1005. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1006. }
  1007. }
  1008. }
  1009. }