sheet.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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.10 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. "reflect"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "unicode/utf8"
  24. "github.com/mohae/deepcopy"
  25. )
  26. // NewSheet provides function to create a new sheet by given worksheet name.
  27. // When creating a new XLSX file, the default sheet will be created. Returns
  28. // the number of sheets in the workbook (file) after appending the new sheet.
  29. func (f *File) NewSheet(name string) int {
  30. // Check if the worksheet already exists
  31. if f.GetSheetIndex(name) != 0 {
  32. return f.SheetCount
  33. }
  34. f.DeleteSheet(name)
  35. f.SheetCount++
  36. wb := f.workbookReader()
  37. sheetID := 0
  38. for _, v := range wb.Sheets.Sheet {
  39. if v.SheetID > sheetID {
  40. sheetID = v.SheetID
  41. }
  42. }
  43. sheetID++
  44. // Update docProps/app.xml
  45. f.setAppXML()
  46. // Update [Content_Types].xml
  47. f.setContentTypes(sheetID)
  48. // Create new sheet /xl/worksheets/sheet%d.xml
  49. f.setSheet(sheetID, name)
  50. // Update xl/_rels/workbook.xml.rels
  51. rID := f.addRels("xl/_rels/workbook.xml.rels", SourceRelationshipWorkSheet, fmt.Sprintf("worksheets/sheet%d.xml", sheetID), "")
  52. // Update xl/workbook.xml
  53. f.setWorkbook(name, sheetID, rID)
  54. return sheetID
  55. }
  56. // contentTypesReader provides a function to get the pointer to the
  57. // [Content_Types].xml structure after deserialization.
  58. func (f *File) contentTypesReader() *xlsxTypes {
  59. if f.ContentTypes == nil {
  60. var content xlsxTypes
  61. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("[Content_Types].xml")), &content)
  62. f.ContentTypes = &content
  63. }
  64. return f.ContentTypes
  65. }
  66. // contentTypesWriter provides a function to save [Content_Types].xml after
  67. // serialize structure.
  68. func (f *File) contentTypesWriter() {
  69. if f.ContentTypes != nil {
  70. output, _ := xml.Marshal(f.ContentTypes)
  71. f.saveFileList("[Content_Types].xml", output)
  72. }
  73. }
  74. // workbookReader provides a function to get the pointer to the xl/workbook.xml
  75. // structure after deserialization.
  76. func (f *File) workbookReader() *xlsxWorkbook {
  77. if f.WorkBook == nil {
  78. var content xlsxWorkbook
  79. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/workbook.xml")), &content)
  80. f.WorkBook = &content
  81. }
  82. return f.WorkBook
  83. }
  84. // workBookWriter provides a function to save xl/workbook.xml after serialize
  85. // structure.
  86. func (f *File) workBookWriter() {
  87. if f.WorkBook != nil {
  88. output, _ := xml.Marshal(f.WorkBook)
  89. f.saveFileList("xl/workbook.xml", replaceRelationshipsBytes(replaceRelationshipsNameSpaceBytes(output)))
  90. }
  91. }
  92. // workSheetWriter provides a function to save xl/worksheets/sheet%d.xml after
  93. // serialize structure.
  94. func (f *File) workSheetWriter() {
  95. for p, sheet := range f.Sheet {
  96. if sheet != nil {
  97. for k, v := range sheet.SheetData.Row {
  98. f.Sheet[p].SheetData.Row[k].C = trimCell(v.C)
  99. }
  100. output, _ := xml.Marshal(sheet)
  101. f.saveFileList(p, replaceRelationshipsBytes(replaceWorkSheetsRelationshipsNameSpaceBytes(output)))
  102. ok := f.checked[p]
  103. if ok {
  104. delete(f.Sheet, p)
  105. f.checked[p] = false
  106. }
  107. }
  108. }
  109. }
  110. // trimCell provides a function to trim blank cells which created by fillColumns.
  111. func trimCell(column []xlsxC) []xlsxC {
  112. rowFull := true
  113. for i := range column {
  114. rowFull = column[i].hasValue() && rowFull
  115. }
  116. if rowFull {
  117. return column
  118. }
  119. col := make([]xlsxC, len(column))
  120. i := 0
  121. for _, c := range column {
  122. if c.hasValue() {
  123. col[i] = c
  124. i++
  125. }
  126. }
  127. return col[0:i]
  128. }
  129. // setContentTypes provides a function to read and update property of contents
  130. // type of XLSX.
  131. func (f *File) setContentTypes(index int) {
  132. content := f.contentTypesReader()
  133. content.Overrides = append(content.Overrides, xlsxOverride{
  134. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  135. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  136. })
  137. }
  138. // setSheet provides a function to update sheet property by given index.
  139. func (f *File) setSheet(index int, name string) {
  140. var xlsx xlsxWorksheet
  141. xlsx.Dimension.Ref = "A1"
  142. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  143. WorkbookViewID: 0,
  144. })
  145. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  146. f.sheetMap[trimSheetName(name)] = path
  147. f.Sheet[path] = &xlsx
  148. }
  149. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  150. // allowed in sheet title.
  151. func (f *File) setWorkbook(name string, sheetID, rid int) {
  152. content := f.workbookReader()
  153. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  154. Name: trimSheetName(name),
  155. SheetID: sheetID,
  156. ID: "rId" + strconv.Itoa(rid),
  157. })
  158. }
  159. // relsWriter provides a function to save relationships after
  160. // serialize structure.
  161. func (f *File) relsWriter() {
  162. for path, rel := range f.Relationships {
  163. if rel != nil {
  164. output, _ := xml.Marshal(rel)
  165. if strings.HasPrefix(path, "xl/worksheets/sheet/rels/sheet") {
  166. output = replaceWorkSheetsRelationshipsNameSpaceBytes(output)
  167. }
  168. f.saveFileList(path, replaceRelationshipsBytes(output))
  169. }
  170. }
  171. }
  172. // setAppXML update docProps/app.xml file of XML.
  173. func (f *File) setAppXML() {
  174. f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
  175. }
  176. // replaceRelationshipsBytes; Some tools that read XLSX files have very strict
  177. // requirements about the structure of the input XML. This function is a
  178. // horrible hack to fix that after the XML marshalling is completed.
  179. func replaceRelationshipsBytes(content []byte) []byte {
  180. oldXmlns := []byte(`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships`)
  181. newXmlns := []byte("r")
  182. return bytes.Replace(content, oldXmlns, newXmlns, -1)
  183. }
  184. // replaceRelationshipsNameSpaceBytes; Some tools that read XLSX files have
  185. // very strict requirements about the structure of the input XML. In
  186. // particular both Numbers on the Mac and SAS dislike inline XML namespace
  187. // declarations, or namespace prefixes that don't match the ones that Excel
  188. // itself uses. This is a problem because the Go XML library doesn't multiple
  189. // namespace declarations in a single element of a document. This function is
  190. // a horrible hack to fix that after the XML marshalling is completed.
  191. func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  192. oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  193. newXmlns := []byte(`<workbook` + templateNamespaceIDMap)
  194. return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  195. }
  196. // SetActiveSheet provides function to set default active worksheet of XLSX by
  197. // given index. Note that active index is different from the index returned by
  198. // function GetSheetMap(). It should be greater than 0 and less than total
  199. // worksheet numbers.
  200. func (f *File) SetActiveSheet(index int) {
  201. if index < 1 {
  202. index = 1
  203. }
  204. wb := f.workbookReader()
  205. for activeTab, sheet := range wb.Sheets.Sheet {
  206. if sheet.SheetID == index {
  207. if len(wb.BookViews.WorkBookView) > 0 {
  208. wb.BookViews.WorkBookView[0].ActiveTab = activeTab
  209. } else {
  210. wb.BookViews.WorkBookView = append(wb.BookViews.WorkBookView, xlsxWorkBookView{
  211. ActiveTab: activeTab,
  212. })
  213. }
  214. }
  215. }
  216. for idx, name := range f.GetSheetMap() {
  217. xlsx, _ := f.workSheetReader(name)
  218. if len(xlsx.SheetViews.SheetView) > 0 {
  219. xlsx.SheetViews.SheetView[0].TabSelected = false
  220. }
  221. if index == idx {
  222. if len(xlsx.SheetViews.SheetView) > 0 {
  223. xlsx.SheetViews.SheetView[0].TabSelected = true
  224. } else {
  225. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  226. TabSelected: true,
  227. })
  228. }
  229. }
  230. }
  231. }
  232. // GetActiveSheetIndex provides a function to get active sheet index of the
  233. // XLSX. If not found the active sheet will be return integer 0.
  234. func (f *File) GetActiveSheetIndex() int {
  235. wb := f.workbookReader()
  236. if wb != nil {
  237. view := wb.BookViews.WorkBookView
  238. sheets := wb.Sheets.Sheet
  239. var activeTab int
  240. if len(view) > 0 {
  241. activeTab = view[0].ActiveTab
  242. if len(sheets) > activeTab && sheets[activeTab].SheetID != 0 {
  243. return sheets[activeTab].SheetID
  244. }
  245. }
  246. if len(wb.Sheets.Sheet) == 1 {
  247. return wb.Sheets.Sheet[0].SheetID
  248. }
  249. }
  250. return 0
  251. }
  252. // SetSheetName provides a function to set the worksheet name be given old and
  253. // new worksheet name. Maximum 31 characters are allowed in sheet title and
  254. // this function only changes the name of the sheet and will not update the
  255. // sheet name in the formula or reference associated with the cell. So there
  256. // may be problem formula error or reference missing.
  257. func (f *File) SetSheetName(oldName, newName string) {
  258. oldName = trimSheetName(oldName)
  259. newName = trimSheetName(newName)
  260. content := f.workbookReader()
  261. for k, v := range content.Sheets.Sheet {
  262. if v.Name == oldName {
  263. content.Sheets.Sheet[k].Name = newName
  264. f.sheetMap[newName] = f.sheetMap[oldName]
  265. delete(f.sheetMap, oldName)
  266. }
  267. }
  268. }
  269. // GetSheetName provides a function to get worksheet name of XLSX by given
  270. // worksheet index. If given sheet index is invalid, will return an empty
  271. // string.
  272. func (f *File) GetSheetName(index int) string {
  273. wb := f.workbookReader()
  274. realIdx := index - 1 // sheets are 1 based index, but we're checking against an array
  275. if wb == nil || realIdx < 0 || realIdx >= len(wb.Sheets.Sheet) {
  276. return ""
  277. }
  278. return wb.Sheets.Sheet[realIdx].Name
  279. }
  280. // GetSheetIndex provides a function to get worksheet index of XLSX by given
  281. // sheet name. If given worksheet name is invalid, will return an integer type
  282. // value 0.
  283. func (f *File) GetSheetIndex(name string) int {
  284. wb := f.workbookReader()
  285. if wb != nil {
  286. for _, sheet := range wb.Sheets.Sheet {
  287. if sheet.Name == trimSheetName(name) {
  288. return sheet.SheetID
  289. }
  290. }
  291. }
  292. return 0
  293. }
  294. // GetSheetMap provides a function to get worksheet name and index map of XLSX.
  295. // For example:
  296. //
  297. // f, err := excelize.OpenFile("./Book1.xlsx")
  298. // if err != nil {
  299. // return
  300. // }
  301. // for index, name := range f.GetSheetMap() {
  302. // fmt.Println(index, name)
  303. // }
  304. //
  305. func (f *File) GetSheetMap() map[int]string {
  306. wb := f.workbookReader()
  307. sheetMap := map[int]string{}
  308. if wb != nil {
  309. for i, sheet := range wb.Sheets.Sheet {
  310. sheetMap[i+1] = sheet.Name
  311. }
  312. }
  313. return sheetMap
  314. }
  315. // getSheetMap provides a function to get worksheet name and XML file path map
  316. // of XLSX.
  317. func (f *File) getSheetMap() map[string]string {
  318. content := f.workbookReader()
  319. rels := f.relsReader("xl/_rels/workbook.xml.rels")
  320. maps := map[string]string{}
  321. for _, v := range content.Sheets.Sheet {
  322. for _, rel := range rels.Relationships {
  323. if rel.ID == v.ID {
  324. // Construct a target XML as xl/worksheets/sheet%d by split path, compatible with different types of relative paths in workbook.xml.rels, for example: worksheets/sheet%d.xml and /xl/worksheets/sheet%d.xml
  325. pathInfo := strings.Split(rel.Target, "/")
  326. pathInfoLen := len(pathInfo)
  327. if pathInfoLen > 0 {
  328. maps[v.Name] = fmt.Sprintf("xl/worksheets/%s", pathInfo[pathInfoLen-1])
  329. }
  330. }
  331. }
  332. }
  333. return maps
  334. }
  335. // SetSheetBackground provides a function to set background picture by given
  336. // worksheet name and file path.
  337. func (f *File) SetSheetBackground(sheet, picture string) error {
  338. var err error
  339. // Check picture exists first.
  340. if _, err = os.Stat(picture); os.IsNotExist(err) {
  341. return err
  342. }
  343. ext, ok := supportImageTypes[path.Ext(picture)]
  344. if !ok {
  345. return errors.New("unsupported image extension")
  346. }
  347. file, _ := ioutil.ReadFile(picture)
  348. name := f.addMedia(file, ext)
  349. sheetPath, _ := f.sheetMap[trimSheetName(sheet)]
  350. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  351. rID := f.addRels(sheetRels, SourceRelationshipImage, strings.Replace(name, "xl", "..", 1), "")
  352. f.addSheetPicture(sheet, rID)
  353. f.setContentTypePartImageExtensions()
  354. return err
  355. }
  356. // DeleteSheet provides a function to delete worksheet in a workbook by given
  357. // worksheet name. Use this method with caution, which will affect changes in
  358. // references such as formulas, charts, and so on. If there is any referenced
  359. // value of the deleted worksheet, it will cause a file error when you open it.
  360. // This function will be invalid when only the one worksheet is left.
  361. func (f *File) DeleteSheet(name string) {
  362. if f.SheetCount == 1 || f.GetSheetIndex(name) == 0 {
  363. return
  364. }
  365. sheetName := trimSheetName(name)
  366. wb := f.workbookReader()
  367. wbRels := f.relsReader("xl/_rels/workbook.xml.rels")
  368. for idx, sheet := range wb.Sheets.Sheet {
  369. if sheet.Name == sheetName {
  370. wb.Sheets.Sheet = append(wb.Sheets.Sheet[:idx], wb.Sheets.Sheet[idx+1:]...)
  371. var sheetXML, rels string
  372. if wbRels != nil {
  373. for _, rel := range wbRels.Relationships {
  374. if rel.ID == sheet.ID {
  375. sheetXML = fmt.Sprintf("xl/%s", rel.Target)
  376. rels = strings.Replace(fmt.Sprintf("xl/%s.rels", rel.Target), "xl/worksheets/", "xl/worksheets/_rels/", -1)
  377. }
  378. }
  379. }
  380. target := f.deleteSheetFromWorkbookRels(sheet.ID)
  381. f.deleteSheetFromContentTypes(target)
  382. f.deleteCalcChain(sheet.SheetID, "") // Delete CalcChain
  383. delete(f.sheetMap, sheetName)
  384. delete(f.XLSX, sheetXML)
  385. delete(f.XLSX, rels)
  386. delete(f.Sheet, sheetXML)
  387. f.SheetCount--
  388. }
  389. }
  390. for idx, bookView := range wb.BookViews.WorkBookView {
  391. if bookView.ActiveTab >= f.SheetCount {
  392. wb.BookViews.WorkBookView[idx].ActiveTab--
  393. }
  394. }
  395. f.SetActiveSheet(len(f.GetSheetMap()))
  396. }
  397. // deleteSheetFromWorkbookRels provides a function to remove worksheet
  398. // relationships by given relationships ID in the file
  399. // xl/_rels/workbook.xml.rels.
  400. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  401. content := f.relsReader("xl/_rels/workbook.xml.rels")
  402. for k, v := range content.Relationships {
  403. if v.ID == rID {
  404. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  405. return v.Target
  406. }
  407. }
  408. return ""
  409. }
  410. // deleteSheetFromContentTypes provides a function to remove worksheet
  411. // relationships by given target name in the file [Content_Types].xml.
  412. func (f *File) deleteSheetFromContentTypes(target string) {
  413. content := f.contentTypesReader()
  414. for k, v := range content.Overrides {
  415. if v.PartName == "/xl/"+target {
  416. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  417. }
  418. }
  419. }
  420. // CopySheet provides a function to duplicate a worksheet by gave source and
  421. // target worksheet index. Note that currently doesn't support duplicate
  422. // workbooks that contain tables, charts or pictures. For Example:
  423. //
  424. // // Sheet1 already exists...
  425. // index := f.NewSheet("Sheet2")
  426. // err := f.CopySheet(1, index)
  427. // return err
  428. //
  429. func (f *File) CopySheet(from, to int) error {
  430. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  431. return errors.New("invalid worksheet index")
  432. }
  433. return f.copySheet(from, to)
  434. }
  435. // copySheet provides a function to duplicate a worksheet by gave source and
  436. // target worksheet name.
  437. func (f *File) copySheet(from, to int) error {
  438. sheet, err := f.workSheetReader(f.GetSheetName(from))
  439. if err != nil {
  440. return err
  441. }
  442. worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
  443. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  444. if len(worksheet.SheetViews.SheetView) > 0 {
  445. worksheet.SheetViews.SheetView[0].TabSelected = false
  446. }
  447. worksheet.Drawing = nil
  448. worksheet.TableParts = nil
  449. worksheet.PageSetUp = nil
  450. f.Sheet[path] = worksheet
  451. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  452. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  453. _, ok := f.XLSX[fromRels]
  454. if ok {
  455. f.XLSX[toRels] = f.XLSX[fromRels]
  456. }
  457. return err
  458. }
  459. // SetSheetVisible provides a function to set worksheet visible by given worksheet
  460. // name. A workbook must contain at least one visible worksheet. If the given
  461. // worksheet has been activated, this setting will be invalidated. Sheet state
  462. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  463. //
  464. // visible
  465. // hidden
  466. // veryHidden
  467. //
  468. // For example, hide Sheet1:
  469. //
  470. // err := f.SetSheetVisible("Sheet1", false)
  471. //
  472. func (f *File) SetSheetVisible(name string, visible bool) error {
  473. name = trimSheetName(name)
  474. content := f.workbookReader()
  475. if visible {
  476. for k, v := range content.Sheets.Sheet {
  477. if v.Name == name {
  478. content.Sheets.Sheet[k].State = ""
  479. }
  480. }
  481. return nil
  482. }
  483. count := 0
  484. for _, v := range content.Sheets.Sheet {
  485. if v.State != "hidden" {
  486. count++
  487. }
  488. }
  489. for k, v := range content.Sheets.Sheet {
  490. xlsx, err := f.workSheetReader(v.Name)
  491. if err != nil {
  492. return err
  493. }
  494. tabSelected := false
  495. if len(xlsx.SheetViews.SheetView) > 0 {
  496. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  497. }
  498. if v.Name == name && count > 1 && !tabSelected {
  499. content.Sheets.Sheet[k].State = "hidden"
  500. }
  501. }
  502. return nil
  503. }
  504. // parseFormatPanesSet provides a function to parse the panes settings.
  505. func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
  506. format := formatPanes{}
  507. err := json.Unmarshal([]byte(formatSet), &format)
  508. return &format, err
  509. }
  510. // SetPanes provides a function to create and remove freeze panes and split panes
  511. // by given worksheet name and panes format set.
  512. //
  513. // activePane defines the pane that is active. The possible values for this
  514. // attribute are defined in the following table:
  515. //
  516. // Enumeration Value | Description
  517. // --------------------------------+-------------------------------------------------------------
  518. // bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
  519. // | splits 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 bottom
  524. // | pane.
  525. // |
  526. // bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
  527. // | splits are applied.
  528. // |
  529. // topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
  530. // | are applied.
  531. // |
  532. // | This value is also used when only a horizontal split has
  533. // | been applied, dividing the pane into upper and lower
  534. // | regions. In that case, this value specifies the top pane.
  535. // |
  536. // | This value is also used when only a vertical split has
  537. // | been applied, dividing the pane into right and left
  538. // | regions. In that case, this value specifies the left pane
  539. // |
  540. // topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
  541. // | splits are applied.
  542. // |
  543. // | This value is also used when only a vertical split has
  544. // | been applied, dividing the pane into right and left
  545. // | regions. In that case, this value specifies the right
  546. // | pane.
  547. //
  548. // Pane state type is restricted to the values supported currently listed in the following table:
  549. //
  550. // Enumeration Value | Description
  551. // --------------------------------+-------------------------------------------------------------
  552. // frozen (Frozen) | Panes are frozen, but were not split being frozen. In
  553. // | this state, when the panes are unfrozen again, a single
  554. // | pane results, with no split.
  555. // |
  556. // | In this state, the split bars are not adjustable.
  557. // |
  558. // split (Split) | Panes are split, but not frozen. In this state, the split
  559. // | bars are adjustable by the user.
  560. //
  561. // x_split (Horizontal Split Position): Horizontal position of the split, in
  562. // 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
  563. // indicates the number of columns visible in the top pane.
  564. //
  565. // y_split (Vertical Split Position): Vertical position of the split, in 1/20th
  566. // of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
  567. // number of rows visible in the left pane. The possible values for this
  568. // attribute are defined by the W3C XML Schema double datatype.
  569. //
  570. // top_left_cell: Location of the top left visible cell in the bottom right pane
  571. // (when in Left-To-Right mode).
  572. //
  573. // sqref (Sequence of References): Range of the selection. Can be non-contiguous
  574. // set of ranges.
  575. //
  576. // An example of how to freeze column A in the Sheet1 and set the active cell on
  577. // Sheet1!K16:
  578. //
  579. // f.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"}]}`)
  580. //
  581. // An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
  582. // ranges on Sheet1!A11:XFD11:
  583. //
  584. // f.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"}]}`)
  585. //
  586. // An example of how to create split panes in the Sheet1 and set the active cell
  587. // on Sheet1!J60:
  588. //
  589. // f.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"}]}`)
  590. //
  591. // An example of how to unfreeze and remove all panes on Sheet1:
  592. //
  593. // f.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
  594. //
  595. func (f *File) SetPanes(sheet, panes string) error {
  596. fs, _ := parseFormatPanesSet(panes)
  597. xlsx, err := f.workSheetReader(sheet)
  598. if err != nil {
  599. return err
  600. }
  601. p := &xlsxPane{
  602. ActivePane: fs.ActivePane,
  603. TopLeftCell: fs.TopLeftCell,
  604. XSplit: float64(fs.XSplit),
  605. YSplit: float64(fs.YSplit),
  606. }
  607. if fs.Freeze {
  608. p.State = "frozen"
  609. }
  610. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
  611. if !(fs.Freeze) && !(fs.Split) {
  612. if len(xlsx.SheetViews.SheetView) > 0 {
  613. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
  614. }
  615. }
  616. s := []*xlsxSelection{}
  617. for _, p := range fs.Panes {
  618. s = append(s, &xlsxSelection{
  619. ActiveCell: p.ActiveCell,
  620. Pane: p.Pane,
  621. SQRef: p.SQRef,
  622. })
  623. }
  624. xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
  625. return err
  626. }
  627. // GetSheetVisible provides a function to get worksheet visible by given worksheet
  628. // name. For example, get visible state of Sheet1:
  629. //
  630. // f.GetSheetVisible("Sheet1")
  631. //
  632. func (f *File) GetSheetVisible(name string) bool {
  633. content := f.workbookReader()
  634. visible := false
  635. for k, v := range content.Sheets.Sheet {
  636. if v.Name == trimSheetName(name) {
  637. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  638. visible = true
  639. }
  640. }
  641. }
  642. return visible
  643. }
  644. // SearchSheet provides a function to get coordinates by given worksheet name,
  645. // cell value, and regular expression. The function doesn't support searching
  646. // on the calculated result, formatted numbers and conditional lookup
  647. // currently. If it is a merged cell, it will return the coordinates of the
  648. // upper left corner of the merged area.
  649. //
  650. // An example of search the coordinates of the value of "100" on Sheet1:
  651. //
  652. // result, err := f.SearchSheet("Sheet1", "100")
  653. //
  654. // An example of search the coordinates where the numerical value in the range
  655. // of "0-9" of Sheet1 is described:
  656. //
  657. // result, err := f.SearchSheet("Sheet1", "[0-9]", true)
  658. //
  659. func (f *File) SearchSheet(sheet, value string, reg ...bool) ([]string, error) {
  660. var (
  661. regSearch bool
  662. result []string
  663. )
  664. for _, r := range reg {
  665. regSearch = r
  666. }
  667. name, ok := f.sheetMap[trimSheetName(sheet)]
  668. if !ok {
  669. return result, ErrSheetNotExist{sheet}
  670. }
  671. if f.Sheet[name] != nil {
  672. // flush data
  673. output, _ := xml.Marshal(f.Sheet[name])
  674. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  675. }
  676. return f.searchSheet(name, value, regSearch)
  677. }
  678. // searchSheet provides a function to get coordinates by given worksheet name,
  679. // cell value, and regular expression.
  680. func (f *File) searchSheet(name, value string, regSearch bool) ([]string, error) {
  681. var (
  682. err error
  683. cellName, inElement string
  684. result []string
  685. cellCol, row int
  686. )
  687. d := f.sharedStringsReader()
  688. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  689. for {
  690. token, _ := decoder.Token()
  691. if token == nil {
  692. break
  693. }
  694. switch startElement := token.(type) {
  695. case xml.StartElement:
  696. inElement = startElement.Name.Local
  697. if inElement == "row" {
  698. for _, attr := range startElement.Attr {
  699. if attr.Name.Local == "r" {
  700. row, err = strconv.Atoi(attr.Value)
  701. if err != nil {
  702. return result, err
  703. }
  704. }
  705. }
  706. }
  707. if inElement == "c" {
  708. colCell := xlsxC{}
  709. _ = decoder.DecodeElement(&colCell, &startElement)
  710. val, _ := colCell.getValueFrom(f, d)
  711. if regSearch {
  712. regex := regexp.MustCompile(value)
  713. if !regex.MatchString(val) {
  714. continue
  715. }
  716. } else {
  717. if val != value {
  718. continue
  719. }
  720. }
  721. cellCol, _, err = CellNameToCoordinates(colCell.R)
  722. if err != nil {
  723. return result, err
  724. }
  725. cellName, err = CoordinatesToCellName(cellCol, row)
  726. if err != nil {
  727. return result, err
  728. }
  729. result = append(result, cellName)
  730. }
  731. default:
  732. }
  733. }
  734. return result, nil
  735. }
  736. // SetHeaderFooter provides a function to set headers and footers by given
  737. // worksheet name and the control characters.
  738. //
  739. // Headers and footers are specified using the following settings fields:
  740. //
  741. // Fields | Description
  742. // ------------------+-----------------------------------------------------------
  743. // AlignWithMargins | Align header footer margins with page margins
  744. // DifferentFirst | Different first-page header and footer indicator
  745. // DifferentOddEven | Different odd and even page headers and footers indicator
  746. // ScaleWithDoc | Scale header and footer with document scaling
  747. // OddFooter | Odd Page Footer
  748. // OddHeader | Odd Header
  749. // EvenFooter | Even Page Footer
  750. // EvenHeader | Even Page Header
  751. // FirstFooter | First Page Footer
  752. // FirstHeader | First Page Header
  753. //
  754. // The following formatting codes can be used in 6 string type fields:
  755. // OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
  756. //
  757. // Formatting Code | Description
  758. // ------------------------+-------------------------------------------------------------------------
  759. // && | The character "&"
  760. // |
  761. // &font-size | Size of the text font, where font-size is a decimal font size in points
  762. // |
  763. // &"font name,font type" | A text font-name string, font name, and a text font-type string,
  764. // | font type
  765. // |
  766. // &"-,Regular" | Regular text format. Toggles bold and italic modes to off
  767. // |
  768. // &A | Current worksheet's tab name
  769. // |
  770. // &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off
  771. // |
  772. // &D | Current date
  773. // |
  774. // &C | Center section
  775. // |
  776. // &E | Double-underline text format
  777. // |
  778. // &F | Current workbook's file name
  779. // |
  780. // &G | Drawing object as background
  781. // |
  782. // &H | Shadow text format
  783. // |
  784. // &I or &"-,Italic" | Italic text format
  785. // |
  786. // &K | Text font color
  787. // |
  788. // | An RGB Color is specified as RRGGBB
  789. // |
  790. // | A Theme Color is specified as TTSNNN where TT is the theme color Id,
  791. // | S is either "+" or "-" of the tint/shade value, and NNN is the
  792. // | tint/shade value
  793. // |
  794. // &L | Left section
  795. // |
  796. // &N | Total number of pages
  797. // |
  798. // &O | Outline text format
  799. // |
  800. // &P[[+|-]n] | Without the optional suffix, the current page number in decimal
  801. // |
  802. // &R | Right section
  803. // |
  804. // &S | Strikethrough text format
  805. // |
  806. // &T | Current time
  807. // |
  808. // &U | Single-underline text format. If double-underline mode is on, the next
  809. // | occurrence in a section specifier toggles double-underline mode to off;
  810. // | otherwise, it toggles single-underline mode, from off to on, or vice
  811. // | versa. The default mode is off
  812. // |
  813. // &X | Superscript text format
  814. // |
  815. // &Y | Subscript text format
  816. // |
  817. // &Z | Current workbook's file path
  818. //
  819. // For example:
  820. //
  821. // err := f.SetHeaderFooter("Sheet1", &excelize.FormatHeaderFooter{
  822. // DifferentFirst: true,
  823. // DifferentOddEven: true,
  824. // OddHeader: "&R&P",
  825. // OddFooter: "&C&F",
  826. // EvenHeader: "&L&P",
  827. // EvenFooter: "&L&D&R&T",
  828. // FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  829. // })
  830. //
  831. // This example shows:
  832. //
  833. // - The first page has its own header and footer
  834. //
  835. // - Odd and even-numbered pages have different headers and footers
  836. //
  837. // - Current page number in the right section of odd-page headers
  838. //
  839. // - Current workbook's file name in the center section of odd-page footers
  840. //
  841. // - Current page number in the left section of even-page headers
  842. //
  843. // - Current date in the left section and the current time in the right section
  844. // of even-page footers
  845. //
  846. // - The text "Center Bold Header" on the first line of the center section of
  847. // the first page, and the date on the second line of the center section of
  848. // that same page
  849. //
  850. // - No footer on the first page
  851. //
  852. func (f *File) SetHeaderFooter(sheet string, settings *FormatHeaderFooter) error {
  853. xlsx, err := f.workSheetReader(sheet)
  854. if err != nil {
  855. return err
  856. }
  857. if settings == nil {
  858. xlsx.HeaderFooter = nil
  859. return err
  860. }
  861. v := reflect.ValueOf(*settings)
  862. // Check 6 string type fields: OddHeader, OddFooter, EvenHeader, EvenFooter,
  863. // FirstFooter, FirstHeader
  864. for i := 4; i < v.NumField()-1; i++ {
  865. if v.Field(i).Len() >= 255 {
  866. return fmt.Errorf("field %s must be less than 255 characters", v.Type().Field(i).Name)
  867. }
  868. }
  869. xlsx.HeaderFooter = &xlsxHeaderFooter{
  870. AlignWithMargins: settings.AlignWithMargins,
  871. DifferentFirst: settings.DifferentFirst,
  872. DifferentOddEven: settings.DifferentOddEven,
  873. ScaleWithDoc: settings.ScaleWithDoc,
  874. OddHeader: settings.OddHeader,
  875. OddFooter: settings.OddFooter,
  876. EvenHeader: settings.EvenHeader,
  877. EvenFooter: settings.EvenFooter,
  878. FirstFooter: settings.FirstFooter,
  879. FirstHeader: settings.FirstHeader,
  880. }
  881. return err
  882. }
  883. // ProtectSheet provides a function to prevent other users from accidentally
  884. // or deliberately changing, moving, or deleting data in a worksheet. For
  885. // example, protect Sheet1 with protection settings:
  886. //
  887. // err := f.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  888. // Password: "password",
  889. // EditScenarios: false,
  890. // })
  891. //
  892. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) error {
  893. xlsx, err := f.workSheetReader(sheet)
  894. if err != nil {
  895. return err
  896. }
  897. if settings == nil {
  898. settings = &FormatSheetProtection{
  899. EditObjects: true,
  900. EditScenarios: true,
  901. SelectLockedCells: true,
  902. }
  903. }
  904. xlsx.SheetProtection = &xlsxSheetProtection{
  905. AutoFilter: settings.AutoFilter,
  906. DeleteColumns: settings.DeleteColumns,
  907. DeleteRows: settings.DeleteRows,
  908. FormatCells: settings.FormatCells,
  909. FormatColumns: settings.FormatColumns,
  910. FormatRows: settings.FormatRows,
  911. InsertColumns: settings.InsertColumns,
  912. InsertHyperlinks: settings.InsertHyperlinks,
  913. InsertRows: settings.InsertRows,
  914. Objects: settings.EditObjects,
  915. PivotTables: settings.PivotTables,
  916. Scenarios: settings.EditScenarios,
  917. SelectLockedCells: settings.SelectLockedCells,
  918. SelectUnlockedCells: settings.SelectUnlockedCells,
  919. Sheet: true,
  920. Sort: settings.Sort,
  921. }
  922. if settings.Password != "" {
  923. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  924. }
  925. return err
  926. }
  927. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  928. func (f *File) UnprotectSheet(sheet string) error {
  929. xlsx, err := f.workSheetReader(sheet)
  930. if err != nil {
  931. return err
  932. }
  933. xlsx.SheetProtection = nil
  934. return err
  935. }
  936. // trimSheetName provides a function to trim invaild characters by given worksheet
  937. // name.
  938. func trimSheetName(name string) string {
  939. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  940. r := make([]rune, 0, 31)
  941. for _, v := range name {
  942. switch v {
  943. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  944. continue
  945. default:
  946. r = append(r, v)
  947. }
  948. if len(r) == 31 {
  949. break
  950. }
  951. }
  952. name = string(r)
  953. }
  954. return name
  955. }
  956. // PageLayoutOption is an option of a page layout of a worksheet. See
  957. // SetPageLayout().
  958. type PageLayoutOption interface {
  959. setPageLayout(layout *xlsxPageSetUp)
  960. }
  961. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  962. type PageLayoutOptionPtr interface {
  963. PageLayoutOption
  964. getPageLayout(layout *xlsxPageSetUp)
  965. }
  966. type (
  967. // PageLayoutOrientation defines the orientation of page layout for a
  968. // worksheet.
  969. PageLayoutOrientation string
  970. // PageLayoutPaperSize defines the paper size of the worksheet
  971. PageLayoutPaperSize int
  972. // FitToHeight specified number of vertical pages to fit on
  973. FitToHeight int
  974. // FitToWidth specified number of horizontal pages to fit on
  975. FitToWidth int
  976. )
  977. const (
  978. // OrientationPortrait indicates page layout orientation id portrait.
  979. OrientationPortrait = "portrait"
  980. // OrientationLandscape indicates page layout orientation id landscape.
  981. OrientationLandscape = "landscape"
  982. )
  983. // setPageLayout provides a method to set the orientation for the worksheet.
  984. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  985. ps.Orientation = string(o)
  986. }
  987. // getPageLayout provides a method to get the orientation for the worksheet.
  988. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  989. // Excel default: portrait
  990. if ps == nil || ps.Orientation == "" {
  991. *o = OrientationPortrait
  992. return
  993. }
  994. *o = PageLayoutOrientation(ps.Orientation)
  995. }
  996. // setPageLayout provides a method to set the paper size for the worksheet.
  997. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  998. ps.PaperSize = int(p)
  999. }
  1000. // getPageLayout provides a method to get the paper size for the worksheet.
  1001. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  1002. // Excel default: 1
  1003. if ps == nil || ps.PaperSize == 0 {
  1004. *p = 1
  1005. return
  1006. }
  1007. *p = PageLayoutPaperSize(ps.PaperSize)
  1008. }
  1009. // setPageLayout provides a method to set the fit to height for the worksheet.
  1010. func (p FitToHeight) setPageLayout(ps *xlsxPageSetUp) {
  1011. if int(p) > 0 {
  1012. ps.FitToHeight = int(p)
  1013. }
  1014. }
  1015. // getPageLayout provides a method to get the fit to height for the worksheet.
  1016. func (p *FitToHeight) getPageLayout(ps *xlsxPageSetUp) {
  1017. if ps == nil || ps.FitToHeight == 0 {
  1018. *p = 1
  1019. return
  1020. }
  1021. *p = FitToHeight(ps.FitToHeight)
  1022. }
  1023. // setPageLayout provides a method to set the fit to width for the worksheet.
  1024. func (p FitToWidth) setPageLayout(ps *xlsxPageSetUp) {
  1025. if int(p) > 0 {
  1026. ps.FitToWidth = int(p)
  1027. }
  1028. }
  1029. // getPageLayout provides a method to get the fit to width for the worksheet.
  1030. func (p *FitToWidth) getPageLayout(ps *xlsxPageSetUp) {
  1031. if ps == nil || ps.FitToWidth == 0 {
  1032. *p = 1
  1033. return
  1034. }
  1035. *p = FitToWidth(ps.FitToWidth)
  1036. }
  1037. // SetPageLayout provides a function to sets worksheet page layout.
  1038. //
  1039. // Available options:
  1040. // PageLayoutOrientation(string)
  1041. // PageLayoutPaperSize(int)
  1042. //
  1043. // The following shows the paper size sorted by excelize index number:
  1044. //
  1045. // Index | Paper Size
  1046. // -------+-----------------------------------------------
  1047. // 1 | Letter paper (8.5 in. by 11 in.)
  1048. // 2 | Letter small paper (8.5 in. by 11 in.)
  1049. // 3 | Tabloid paper (11 in. by 17 in.)
  1050. // 4 | Ledger paper (17 in. by 11 in.)
  1051. // 5 | Legal paper (8.5 in. by 14 in.)
  1052. // 6 | Statement paper (5.5 in. by 8.5 in.)
  1053. // 7 | Executive paper (7.25 in. by 10.5 in.)
  1054. // 8 | A3 paper (297 mm by 420 mm)
  1055. // 9 | A4 paper (210 mm by 297 mm)
  1056. // 10 | A4 small paper (210 mm by 297 mm)
  1057. // 11 | A5 paper (148 mm by 210 mm)
  1058. // 12 | B4 paper (250 mm by 353 mm)
  1059. // 13 | B5 paper (176 mm by 250 mm)
  1060. // 14 | Folio paper (8.5 in. by 13 in.)
  1061. // 15 | Quarto paper (215 mm by 275 mm)
  1062. // 16 | Standard paper (10 in. by 14 in.)
  1063. // 17 | Standard paper (11 in. by 17 in.)
  1064. // 18 | Note paper (8.5 in. by 11 in.)
  1065. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  1066. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  1067. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  1068. // 22 | #12 envelope (4.75 in. by 11 in.)
  1069. // 23 | #14 envelope (5 in. by 11.5 in.)
  1070. // 24 | C paper (17 in. by 22 in.)
  1071. // 25 | D paper (22 in. by 34 in.)
  1072. // 26 | E paper (34 in. by 44 in.)
  1073. // 27 | DL envelope (110 mm by 220 mm)
  1074. // 28 | C5 envelope (162 mm by 229 mm)
  1075. // 29 | C3 envelope (324 mm by 458 mm)
  1076. // 30 | C4 envelope (229 mm by 324 mm)
  1077. // 31 | C6 envelope (114 mm by 162 mm)
  1078. // 32 | C65 envelope (114 mm by 229 mm)
  1079. // 33 | B4 envelope (250 mm by 353 mm)
  1080. // 34 | B5 envelope (176 mm by 250 mm)
  1081. // 35 | B6 envelope (176 mm by 125 mm)
  1082. // 36 | Italy envelope (110 mm by 230 mm)
  1083. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  1084. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  1085. // 39 | US standard fanfold (14.875 in. by 11 in.)
  1086. // 40 | German standard fanfold (8.5 in. by 12 in.)
  1087. // 41 | German legal fanfold (8.5 in. by 13 in.)
  1088. // 42 | ISO B4 (250 mm by 353 mm)
  1089. // 43 | Japanese postcard (100 mm by 148 mm)
  1090. // 44 | Standard paper (9 in. by 11 in.)
  1091. // 45 | Standard paper (10 in. by 11 in.)
  1092. // 46 | Standard paper (15 in. by 11 in.)
  1093. // 47 | Invite envelope (220 mm by 220 mm)
  1094. // 50 | Letter extra paper (9.275 in. by 12 in.)
  1095. // 51 | Legal extra paper (9.275 in. by 15 in.)
  1096. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  1097. // 53 | A4 extra paper (236 mm by 322 mm)
  1098. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  1099. // 55 | A4 transverse paper (210 mm by 297 mm)
  1100. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  1101. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  1102. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  1103. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  1104. // 60 | A4 plus paper (210 mm by 330 mm)
  1105. // 61 | A5 transverse paper (148 mm by 210 mm)
  1106. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  1107. // 63 | A3 extra paper (322 mm by 445 mm)
  1108. // 64 | A5 extra paper (174 mm by 235 mm)
  1109. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  1110. // 66 | A2 paper (420 mm by 594 mm)
  1111. // 67 | A3 transverse paper (297 mm by 420 mm)
  1112. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  1113. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  1114. // 70 | A6 (105 mm x 148 mm)
  1115. // 71 | Japanese Envelope Kaku #2
  1116. // 72 | Japanese Envelope Kaku #3
  1117. // 73 | Japanese Envelope Chou #3
  1118. // 74 | Japanese Envelope Chou #4
  1119. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  1120. // 76 | A3 Rotated (420 mm x 297 mm)
  1121. // 77 | A4 Rotated (297 mm x 210 mm)
  1122. // 78 | A5 Rotated (210 mm x 148 mm)
  1123. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  1124. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  1125. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  1126. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  1127. // 83 | A6 Rotated (148 mm x 105 mm)
  1128. // 84 | Japanese Envelope Kaku #2 Rotated
  1129. // 85 | Japanese Envelope Kaku #3 Rotated
  1130. // 86 | Japanese Envelope Chou #3 Rotated
  1131. // 87 | Japanese Envelope Chou #4 Rotated
  1132. // 88 | B6 (JIS) (128 mm x 182 mm)
  1133. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  1134. // 90 | (12 in x 11 in)
  1135. // 91 | Japanese Envelope You #4
  1136. // 92 | Japanese Envelope You #4 Rotated
  1137. // 93 | PRC 16K (146 mm x 215 mm)
  1138. // 94 | PRC 32K (97 mm x 151 mm)
  1139. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  1140. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  1141. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  1142. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  1143. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  1144. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  1145. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  1146. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  1147. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  1148. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  1149. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  1150. // 106 | PRC 16K Rotated
  1151. // 107 | PRC 32K Rotated
  1152. // 108 | PRC 32K(Big) Rotated
  1153. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  1154. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  1155. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  1156. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  1157. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  1158. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  1159. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  1160. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  1161. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  1162. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  1163. //
  1164. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  1165. s, err := f.workSheetReader(sheet)
  1166. if err != nil {
  1167. return err
  1168. }
  1169. ps := s.PageSetUp
  1170. if ps == nil {
  1171. ps = new(xlsxPageSetUp)
  1172. s.PageSetUp = ps
  1173. }
  1174. for _, opt := range opts {
  1175. opt.setPageLayout(ps)
  1176. }
  1177. return err
  1178. }
  1179. // GetPageLayout provides a function to gets worksheet page layout.
  1180. //
  1181. // Available options:
  1182. // PageLayoutOrientation(string)
  1183. // PageLayoutPaperSize(int)
  1184. // FitToHeight(int)
  1185. // FitToWidth(int)
  1186. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  1187. s, err := f.workSheetReader(sheet)
  1188. if err != nil {
  1189. return err
  1190. }
  1191. ps := s.PageSetUp
  1192. for _, opt := range opts {
  1193. opt.getPageLayout(ps)
  1194. }
  1195. return err
  1196. }
  1197. // SetDefinedName provides a function to set the defined names of the workbook
  1198. // or worksheet. If not specified scope, the default scope is workbook.
  1199. // For example:
  1200. //
  1201. // f.SetDefinedName(&excelize.DefinedName{
  1202. // Name: "Amount",
  1203. // RefersTo: "Sheet1!$A$2:$D$5",
  1204. // Comment: "defined name comment",
  1205. // Scope: "Sheet2",
  1206. // })
  1207. //
  1208. func (f *File) SetDefinedName(definedName *DefinedName) error {
  1209. wb := f.workbookReader()
  1210. d := xlsxDefinedName{
  1211. Name: definedName.Name,
  1212. Comment: definedName.Comment,
  1213. Data: definedName.RefersTo,
  1214. }
  1215. if definedName.Scope != "" {
  1216. if sheetID := f.GetSheetIndex(definedName.Scope); sheetID != 0 {
  1217. sheetID--
  1218. d.LocalSheetID = &sheetID
  1219. }
  1220. }
  1221. if wb.DefinedNames != nil {
  1222. for _, dn := range wb.DefinedNames.DefinedName {
  1223. var scope string
  1224. if dn.LocalSheetID != nil {
  1225. scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1226. }
  1227. if scope == definedName.Scope && dn.Name == definedName.Name {
  1228. return errors.New("the same name already exists on the scope")
  1229. }
  1230. }
  1231. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d)
  1232. return nil
  1233. }
  1234. wb.DefinedNames = &xlsxDefinedNames{
  1235. DefinedName: []xlsxDefinedName{d},
  1236. }
  1237. return nil
  1238. }
  1239. // DeleteDefinedName provides a function to delete the defined names of the
  1240. // workbook or worksheet. If not specified scope, the default scope is
  1241. // workbook. For example:
  1242. //
  1243. // f.DeleteDefinedName(&excelize.DefinedName{
  1244. // Name: "Amount",
  1245. // Scope: "Sheet2",
  1246. // })
  1247. //
  1248. func (f *File) DeleteDefinedName(definedName *DefinedName) error {
  1249. wb := f.workbookReader()
  1250. if wb.DefinedNames != nil {
  1251. for idx, dn := range wb.DefinedNames.DefinedName {
  1252. var scope string
  1253. if dn.LocalSheetID != nil {
  1254. scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1255. }
  1256. if scope == definedName.Scope && dn.Name == definedName.Name {
  1257. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
  1258. return nil
  1259. }
  1260. }
  1261. }
  1262. return errors.New("no defined name on the scope")
  1263. }
  1264. // GetDefinedName provides a function to get the defined names of the workbook
  1265. // or worksheet.
  1266. func (f *File) GetDefinedName() []DefinedName {
  1267. var definedNames []DefinedName
  1268. wb := f.workbookReader()
  1269. if wb.DefinedNames != nil {
  1270. for _, dn := range wb.DefinedNames.DefinedName {
  1271. definedName := DefinedName{
  1272. Name: dn.Name,
  1273. Comment: dn.Comment,
  1274. RefersTo: dn.Data,
  1275. Scope: "Workbook",
  1276. }
  1277. if dn.LocalSheetID != nil {
  1278. definedName.Scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1279. }
  1280. definedNames = append(definedNames, definedName)
  1281. }
  1282. }
  1283. return definedNames
  1284. }
  1285. // GroupSheets provides a function to group worksheets by given worksheets
  1286. // name. Group worksheets must contain an active worksheet.
  1287. func (f *File) GroupSheets(sheets []string) error {
  1288. // check an active worksheet in group worksheets
  1289. var inActiveSheet bool
  1290. activeSheet := f.GetActiveSheetIndex()
  1291. sheetMap := f.GetSheetMap()
  1292. for idx, sheetName := range sheetMap {
  1293. for _, s := range sheets {
  1294. if s == sheetName && idx == activeSheet {
  1295. inActiveSheet = true
  1296. }
  1297. }
  1298. }
  1299. if !inActiveSheet {
  1300. return errors.New("group worksheet must contain an active worksheet")
  1301. }
  1302. // check worksheet exists
  1303. ws := []*xlsxWorksheet{}
  1304. for _, sheet := range sheets {
  1305. xlsx, err := f.workSheetReader(sheet)
  1306. if err != nil {
  1307. return err
  1308. }
  1309. ws = append(ws, xlsx)
  1310. }
  1311. for _, s := range ws {
  1312. sheetViews := s.SheetViews.SheetView
  1313. if len(sheetViews) > 0 {
  1314. for idx := range sheetViews {
  1315. s.SheetViews.SheetView[idx].TabSelected = true
  1316. }
  1317. continue
  1318. }
  1319. }
  1320. return nil
  1321. }
  1322. // UngroupSheets provides a function to ungroup worksheets.
  1323. func (f *File) UngroupSheets() error {
  1324. activeSheet := f.GetActiveSheetIndex()
  1325. sheetMap := f.GetSheetMap()
  1326. for sheetID, sheet := range sheetMap {
  1327. if activeSheet == sheetID {
  1328. continue
  1329. }
  1330. xlsx, _ := f.workSheetReader(sheet)
  1331. sheetViews := xlsx.SheetViews.SheetView
  1332. if len(sheetViews) > 0 {
  1333. for idx := range sheetViews {
  1334. xlsx.SheetViews.SheetView[idx].TabSelected = false
  1335. }
  1336. }
  1337. }
  1338. return nil
  1339. }
  1340. // relsReader provides a function to get the pointer to the structure
  1341. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1342. func (f *File) relsReader(path string) *xlsxRelationships {
  1343. if f.Relationships[path] == nil {
  1344. _, ok := f.XLSX[path]
  1345. if ok {
  1346. c := xlsxRelationships{}
  1347. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &c)
  1348. f.Relationships[path] = &c
  1349. }
  1350. }
  1351. return f.Relationships[path]
  1352. }
  1353. // fillSheetData ensures there are enough rows, and columns in the chosen
  1354. // row to accept data. Missing rows are backfilled and given their row number
  1355. // Uses the last populated row as a hint for the size of the next row to add
  1356. func prepareSheetXML(xlsx *xlsxWorksheet, col int, row int) {
  1357. rowCount := len(xlsx.SheetData.Row)
  1358. sizeHint := 0
  1359. if rowCount > 0 {
  1360. sizeHint = len(xlsx.SheetData.Row[rowCount-1].C)
  1361. }
  1362. if rowCount < row {
  1363. // append missing rows
  1364. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1365. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{R: rowIdx + 1, C: make([]xlsxC, 0, sizeHint)})
  1366. }
  1367. }
  1368. rowData := &xlsx.SheetData.Row[row-1]
  1369. fillColumns(rowData, col, row)
  1370. }
  1371. func fillColumns(rowData *xlsxRow, col, row int) {
  1372. cellCount := len(rowData.C)
  1373. if cellCount < col {
  1374. for colIdx := cellCount; colIdx < col; colIdx++ {
  1375. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1376. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1377. }
  1378. }
  1379. }
  1380. func makeContiguousColumns(xlsx *xlsxWorksheet, fromRow, toRow, colCount int) {
  1381. for ; fromRow < toRow; fromRow++ {
  1382. rowData := &xlsx.SheetData.Row[fromRow-1]
  1383. fillColumns(rowData, colCount, fromRow)
  1384. }
  1385. }