sheet.go 49 KB

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