sheet.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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 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">`)
  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. xlsx, err := f.workSheetReader(sheet)
  668. if err != nil {
  669. return result, err
  670. }
  671. name, ok := f.sheetMap[trimSheetName(sheet)]
  672. if !ok {
  673. return result, nil
  674. }
  675. if xlsx != nil {
  676. output, _ := xml.Marshal(f.Sheet[name])
  677. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  678. }
  679. return f.searchSheet(name, value, regSearch)
  680. }
  681. // searchSheet provides a function to get coordinates by given worksheet name,
  682. // cell value, and regular expression.
  683. func (f *File) searchSheet(name, value string, regSearch bool) ([]string, error) {
  684. var (
  685. inElement string
  686. result []string
  687. r xlsxRow
  688. )
  689. d := f.sharedStringsReader()
  690. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  691. for {
  692. token, _ := decoder.Token()
  693. if token == nil {
  694. break
  695. }
  696. switch startElement := token.(type) {
  697. case xml.StartElement:
  698. inElement = startElement.Name.Local
  699. if inElement == "row" {
  700. r = xlsxRow{}
  701. _ = decoder.DecodeElement(&r, &startElement)
  702. for _, colCell := range r.C {
  703. val, _ := colCell.getValueFrom(f, d)
  704. if regSearch {
  705. regex := regexp.MustCompile(value)
  706. if !regex.MatchString(val) {
  707. continue
  708. }
  709. } else {
  710. if val != value {
  711. continue
  712. }
  713. }
  714. cellCol, _, err := CellNameToCoordinates(colCell.R)
  715. if err != nil {
  716. return result, err
  717. }
  718. cellName, err := CoordinatesToCellName(cellCol, r.R)
  719. if err != nil {
  720. return result, err
  721. }
  722. result = append(result, cellName)
  723. }
  724. }
  725. default:
  726. }
  727. }
  728. return result, nil
  729. }
  730. // SetHeaderFooter provides a function to set headers and footers by given
  731. // worksheet name and the control characters.
  732. //
  733. // Headers and footers are specified using the following settings fields:
  734. //
  735. // Fields | Description
  736. // ------------------+-----------------------------------------------------------
  737. // AlignWithMargins | Align header footer margins with page margins
  738. // DifferentFirst | Different first-page header and footer indicator
  739. // DifferentOddEven | Different odd and even page headers and footers indicator
  740. // ScaleWithDoc | Scale header and footer with document scaling
  741. // OddFooter | Odd Page Footer
  742. // OddHeader | Odd Header
  743. // EvenFooter | Even Page Footer
  744. // EvenHeader | Even Page Header
  745. // FirstFooter | First Page Footer
  746. // FirstHeader | First Page Header
  747. //
  748. // The following formatting codes can be used in 6 string type fields:
  749. // OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
  750. //
  751. // Formatting Code | Description
  752. // ------------------------+-------------------------------------------------------------------------
  753. // && | The character "&"
  754. // |
  755. // &font-size | Size of the text font, where font-size is a decimal font size in points
  756. // |
  757. // &"font name,font type" | A text font-name string, font name, and a text font-type string,
  758. // | font type
  759. // |
  760. // &"-,Regular" | Regular text format. Toggles bold and italic modes to off
  761. // |
  762. // &A | Current worksheet's tab name
  763. // |
  764. // &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off
  765. // |
  766. // &D | Current date
  767. // |
  768. // &C | Center section
  769. // |
  770. // &E | Double-underline text format
  771. // |
  772. // &F | Current workbook's file name
  773. // |
  774. // &G | Drawing object as background
  775. // |
  776. // &H | Shadow text format
  777. // |
  778. // &I or &"-,Italic" | Italic text format
  779. // |
  780. // &K | Text font color
  781. // |
  782. // | An RGB Color is specified as RRGGBB
  783. // |
  784. // | A Theme Color is specified as TTSNNN where TT is the theme color Id,
  785. // | S is either "+" or "-" of the tint/shade value, and NNN is the
  786. // | tint/shade value
  787. // |
  788. // &L | Left section
  789. // |
  790. // &N | Total number of pages
  791. // |
  792. // &O | Outline text format
  793. // |
  794. // &P[[+|-]n] | Without the optional suffix, the current page number in decimal
  795. // |
  796. // &R | Right section
  797. // |
  798. // &S | Strikethrough text format
  799. // |
  800. // &T | Current time
  801. // |
  802. // &U | Single-underline text format. If double-underline mode is on, the next
  803. // | occurrence in a section specifier toggles double-underline mode to off;
  804. // | otherwise, it toggles single-underline mode, from off to on, or vice
  805. // | versa. The default mode is off
  806. // |
  807. // &X | Superscript text format
  808. // |
  809. // &Y | Subscript text format
  810. // |
  811. // &Z | Current workbook's file path
  812. //
  813. // For example:
  814. //
  815. // err := f.SetHeaderFooter("Sheet1", &excelize.FormatHeaderFooter{
  816. // DifferentFirst: true,
  817. // DifferentOddEven: true,
  818. // OddHeader: "&R&P",
  819. // OddFooter: "&C&F",
  820. // EvenHeader: "&L&P",
  821. // EvenFooter: "&L&D&R&T",
  822. // FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  823. // })
  824. //
  825. // This example shows:
  826. //
  827. // - The first page has its own header and footer
  828. //
  829. // - Odd and even-numbered pages have different headers and footers
  830. //
  831. // - Current page number in the right section of odd-page headers
  832. //
  833. // - Current workbook's file name in the center section of odd-page footers
  834. //
  835. // - Current page number in the left section of even-page headers
  836. //
  837. // - Current date in the left section and the current time in the right section
  838. // of even-page footers
  839. //
  840. // - The text "Center Bold Header" on the first line of the center section of
  841. // the first page, and the date on the second line of the center section of
  842. // that same page
  843. //
  844. // - No footer on the first page
  845. //
  846. func (f *File) SetHeaderFooter(sheet string, settings *FormatHeaderFooter) error {
  847. xlsx, err := f.workSheetReader(sheet)
  848. if err != nil {
  849. return err
  850. }
  851. if settings == nil {
  852. xlsx.HeaderFooter = nil
  853. return err
  854. }
  855. v := reflect.ValueOf(*settings)
  856. // Check 6 string type fields: OddHeader, OddFooter, EvenHeader, EvenFooter,
  857. // FirstFooter, FirstHeader
  858. for i := 4; i < v.NumField()-1; i++ {
  859. if v.Field(i).Len() >= 255 {
  860. return fmt.Errorf("field %s must be less than 255 characters", v.Type().Field(i).Name)
  861. }
  862. }
  863. xlsx.HeaderFooter = &xlsxHeaderFooter{
  864. AlignWithMargins: settings.AlignWithMargins,
  865. DifferentFirst: settings.DifferentFirst,
  866. DifferentOddEven: settings.DifferentOddEven,
  867. ScaleWithDoc: settings.ScaleWithDoc,
  868. OddHeader: settings.OddHeader,
  869. OddFooter: settings.OddFooter,
  870. EvenHeader: settings.EvenHeader,
  871. EvenFooter: settings.EvenFooter,
  872. FirstFooter: settings.FirstFooter,
  873. FirstHeader: settings.FirstHeader,
  874. }
  875. return err
  876. }
  877. // ProtectSheet provides a function to prevent other users from accidentally
  878. // or deliberately changing, moving, or deleting data in a worksheet. For
  879. // example, protect Sheet1 with protection settings:
  880. //
  881. // err := f.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
  882. // Password: "password",
  883. // EditScenarios: false,
  884. // })
  885. //
  886. func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) error {
  887. xlsx, err := f.workSheetReader(sheet)
  888. if err != nil {
  889. return err
  890. }
  891. if settings == nil {
  892. settings = &FormatSheetProtection{
  893. EditObjects: true,
  894. EditScenarios: true,
  895. SelectLockedCells: true,
  896. }
  897. }
  898. xlsx.SheetProtection = &xlsxSheetProtection{
  899. AutoFilter: settings.AutoFilter,
  900. DeleteColumns: settings.DeleteColumns,
  901. DeleteRows: settings.DeleteRows,
  902. FormatCells: settings.FormatCells,
  903. FormatColumns: settings.FormatColumns,
  904. FormatRows: settings.FormatRows,
  905. InsertColumns: settings.InsertColumns,
  906. InsertHyperlinks: settings.InsertHyperlinks,
  907. InsertRows: settings.InsertRows,
  908. Objects: settings.EditObjects,
  909. PivotTables: settings.PivotTables,
  910. Scenarios: settings.EditScenarios,
  911. SelectLockedCells: settings.SelectLockedCells,
  912. SelectUnlockedCells: settings.SelectUnlockedCells,
  913. Sheet: true,
  914. Sort: settings.Sort,
  915. }
  916. if settings.Password != "" {
  917. xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
  918. }
  919. return err
  920. }
  921. // UnprotectSheet provides a function to unprotect an Excel worksheet.
  922. func (f *File) UnprotectSheet(sheet string) error {
  923. xlsx, err := f.workSheetReader(sheet)
  924. if err != nil {
  925. return err
  926. }
  927. xlsx.SheetProtection = nil
  928. return err
  929. }
  930. // trimSheetName provides a function to trim invaild characters by given worksheet
  931. // name.
  932. func trimSheetName(name string) string {
  933. if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
  934. r := make([]rune, 0, 31)
  935. for _, v := range name {
  936. switch v {
  937. case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
  938. continue
  939. default:
  940. r = append(r, v)
  941. }
  942. if len(r) == 31 {
  943. break
  944. }
  945. }
  946. name = string(r)
  947. }
  948. return name
  949. }
  950. // PageLayoutOption is an option of a page layout of a worksheet. See
  951. // SetPageLayout().
  952. type PageLayoutOption interface {
  953. setPageLayout(layout *xlsxPageSetUp)
  954. }
  955. // PageLayoutOptionPtr is a writable PageLayoutOption. See GetPageLayout().
  956. type PageLayoutOptionPtr interface {
  957. PageLayoutOption
  958. getPageLayout(layout *xlsxPageSetUp)
  959. }
  960. type (
  961. // PageLayoutOrientation defines the orientation of page layout for a
  962. // worksheet.
  963. PageLayoutOrientation string
  964. // PageLayoutPaperSize defines the paper size of the worksheet
  965. PageLayoutPaperSize int
  966. // FitToHeight specified number of vertical pages to fit on
  967. FitToHeight int
  968. // FitToWidth specified number of horizontal pages to fit on
  969. FitToWidth int
  970. )
  971. const (
  972. // OrientationPortrait indicates page layout orientation id portrait.
  973. OrientationPortrait = "portrait"
  974. // OrientationLandscape indicates page layout orientation id landscape.
  975. OrientationLandscape = "landscape"
  976. )
  977. // setPageLayout provides a method to set the orientation for the worksheet.
  978. func (o PageLayoutOrientation) setPageLayout(ps *xlsxPageSetUp) {
  979. ps.Orientation = string(o)
  980. }
  981. // getPageLayout provides a method to get the orientation for the worksheet.
  982. func (o *PageLayoutOrientation) getPageLayout(ps *xlsxPageSetUp) {
  983. // Excel default: portrait
  984. if ps == nil || ps.Orientation == "" {
  985. *o = OrientationPortrait
  986. return
  987. }
  988. *o = PageLayoutOrientation(ps.Orientation)
  989. }
  990. // setPageLayout provides a method to set the paper size for the worksheet.
  991. func (p PageLayoutPaperSize) setPageLayout(ps *xlsxPageSetUp) {
  992. ps.PaperSize = int(p)
  993. }
  994. // getPageLayout provides a method to get the paper size for the worksheet.
  995. func (p *PageLayoutPaperSize) getPageLayout(ps *xlsxPageSetUp) {
  996. // Excel default: 1
  997. if ps == nil || ps.PaperSize == 0 {
  998. *p = 1
  999. return
  1000. }
  1001. *p = PageLayoutPaperSize(ps.PaperSize)
  1002. }
  1003. // setPageLayout provides a method to set the fit to height for the worksheet.
  1004. func (p FitToHeight) setPageLayout(ps *xlsxPageSetUp) {
  1005. if int(p) > 0 {
  1006. ps.FitToHeight = int(p)
  1007. }
  1008. }
  1009. // getPageLayout provides a method to get the fit to height for the worksheet.
  1010. func (p *FitToHeight) getPageLayout(ps *xlsxPageSetUp) {
  1011. if ps == nil || ps.FitToHeight == 0 {
  1012. *p = 1
  1013. return
  1014. }
  1015. *p = FitToHeight(ps.FitToHeight)
  1016. }
  1017. // setPageLayout provides a method to set the fit to width for the worksheet.
  1018. func (p FitToWidth) setPageLayout(ps *xlsxPageSetUp) {
  1019. if int(p) > 0 {
  1020. ps.FitToWidth = int(p)
  1021. }
  1022. }
  1023. // getPageLayout provides a method to get the fit to width for the worksheet.
  1024. func (p *FitToWidth) getPageLayout(ps *xlsxPageSetUp) {
  1025. if ps == nil || ps.FitToWidth == 0 {
  1026. *p = 1
  1027. return
  1028. }
  1029. *p = FitToWidth(ps.FitToWidth)
  1030. }
  1031. // SetPageLayout provides a function to sets worksheet page layout.
  1032. //
  1033. // Available options:
  1034. // PageLayoutOrientation(string)
  1035. // PageLayoutPaperSize(int)
  1036. //
  1037. // The following shows the paper size sorted by excelize index number:
  1038. //
  1039. // Index | Paper Size
  1040. // -------+-----------------------------------------------
  1041. // 1 | Letter paper (8.5 in. by 11 in.)
  1042. // 2 | Letter small paper (8.5 in. by 11 in.)
  1043. // 3 | Tabloid paper (11 in. by 17 in.)
  1044. // 4 | Ledger paper (17 in. by 11 in.)
  1045. // 5 | Legal paper (8.5 in. by 14 in.)
  1046. // 6 | Statement paper (5.5 in. by 8.5 in.)
  1047. // 7 | Executive paper (7.25 in. by 10.5 in.)
  1048. // 8 | A3 paper (297 mm by 420 mm)
  1049. // 9 | A4 paper (210 mm by 297 mm)
  1050. // 10 | A4 small paper (210 mm by 297 mm)
  1051. // 11 | A5 paper (148 mm by 210 mm)
  1052. // 12 | B4 paper (250 mm by 353 mm)
  1053. // 13 | B5 paper (176 mm by 250 mm)
  1054. // 14 | Folio paper (8.5 in. by 13 in.)
  1055. // 15 | Quarto paper (215 mm by 275 mm)
  1056. // 16 | Standard paper (10 in. by 14 in.)
  1057. // 17 | Standard paper (11 in. by 17 in.)
  1058. // 18 | Note paper (8.5 in. by 11 in.)
  1059. // 19 | #9 envelope (3.875 in. by 8.875 in.)
  1060. // 20 | #10 envelope (4.125 in. by 9.5 in.)
  1061. // 21 | #11 envelope (4.5 in. by 10.375 in.)
  1062. // 22 | #12 envelope (4.75 in. by 11 in.)
  1063. // 23 | #14 envelope (5 in. by 11.5 in.)
  1064. // 24 | C paper (17 in. by 22 in.)
  1065. // 25 | D paper (22 in. by 34 in.)
  1066. // 26 | E paper (34 in. by 44 in.)
  1067. // 27 | DL envelope (110 mm by 220 mm)
  1068. // 28 | C5 envelope (162 mm by 229 mm)
  1069. // 29 | C3 envelope (324 mm by 458 mm)
  1070. // 30 | C4 envelope (229 mm by 324 mm)
  1071. // 31 | C6 envelope (114 mm by 162 mm)
  1072. // 32 | C65 envelope (114 mm by 229 mm)
  1073. // 33 | B4 envelope (250 mm by 353 mm)
  1074. // 34 | B5 envelope (176 mm by 250 mm)
  1075. // 35 | B6 envelope (176 mm by 125 mm)
  1076. // 36 | Italy envelope (110 mm by 230 mm)
  1077. // 37 | Monarch envelope (3.875 in. by 7.5 in.).
  1078. // 38 | 6 3/4 envelope (3.625 in. by 6.5 in.)
  1079. // 39 | US standard fanfold (14.875 in. by 11 in.)
  1080. // 40 | German standard fanfold (8.5 in. by 12 in.)
  1081. // 41 | German legal fanfold (8.5 in. by 13 in.)
  1082. // 42 | ISO B4 (250 mm by 353 mm)
  1083. // 43 | Japanese postcard (100 mm by 148 mm)
  1084. // 44 | Standard paper (9 in. by 11 in.)
  1085. // 45 | Standard paper (10 in. by 11 in.)
  1086. // 46 | Standard paper (15 in. by 11 in.)
  1087. // 47 | Invite envelope (220 mm by 220 mm)
  1088. // 50 | Letter extra paper (9.275 in. by 12 in.)
  1089. // 51 | Legal extra paper (9.275 in. by 15 in.)
  1090. // 52 | Tabloid extra paper (11.69 in. by 18 in.)
  1091. // 53 | A4 extra paper (236 mm by 322 mm)
  1092. // 54 | Letter transverse paper (8.275 in. by 11 in.)
  1093. // 55 | A4 transverse paper (210 mm by 297 mm)
  1094. // 56 | Letter extra transverse paper (9.275 in. by 12 in.)
  1095. // 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm)
  1096. // 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm)
  1097. // 59 | Letter plus paper (8.5 in. by 12.69 in.)
  1098. // 60 | A4 plus paper (210 mm by 330 mm)
  1099. // 61 | A5 transverse paper (148 mm by 210 mm)
  1100. // 62 | JIS B5 transverse paper (182 mm by 257 mm)
  1101. // 63 | A3 extra paper (322 mm by 445 mm)
  1102. // 64 | A5 extra paper (174 mm by 235 mm)
  1103. // 65 | ISO B5 extra paper (201 mm by 276 mm)
  1104. // 66 | A2 paper (420 mm by 594 mm)
  1105. // 67 | A3 transverse paper (297 mm by 420 mm)
  1106. // 68 | A3 extra transverse paper (322 mm by 445 mm)
  1107. // 69 | Japanese Double Postcard (200 mm x 148 mm)
  1108. // 70 | A6 (105 mm x 148 mm)
  1109. // 71 | Japanese Envelope Kaku #2
  1110. // 72 | Japanese Envelope Kaku #3
  1111. // 73 | Japanese Envelope Chou #3
  1112. // 74 | Japanese Envelope Chou #4
  1113. // 75 | Letter Rotated (11in x 8 1/2 11 in)
  1114. // 76 | A3 Rotated (420 mm x 297 mm)
  1115. // 77 | A4 Rotated (297 mm x 210 mm)
  1116. // 78 | A5 Rotated (210 mm x 148 mm)
  1117. // 79 | B4 (JIS) Rotated (364 mm x 257 mm)
  1118. // 80 | B5 (JIS) Rotated (257 mm x 182 mm)
  1119. // 81 | Japanese Postcard Rotated (148 mm x 100 mm)
  1120. // 82 | Double Japanese Postcard Rotated (148 mm x 200 mm)
  1121. // 83 | A6 Rotated (148 mm x 105 mm)
  1122. // 84 | Japanese Envelope Kaku #2 Rotated
  1123. // 85 | Japanese Envelope Kaku #3 Rotated
  1124. // 86 | Japanese Envelope Chou #3 Rotated
  1125. // 87 | Japanese Envelope Chou #4 Rotated
  1126. // 88 | B6 (JIS) (128 mm x 182 mm)
  1127. // 89 | B6 (JIS) Rotated (182 mm x 128 mm)
  1128. // 90 | (12 in x 11 in)
  1129. // 91 | Japanese Envelope You #4
  1130. // 92 | Japanese Envelope You #4 Rotated
  1131. // 93 | PRC 16K (146 mm x 215 mm)
  1132. // 94 | PRC 32K (97 mm x 151 mm)
  1133. // 95 | PRC 32K(Big) (97 mm x 151 mm)
  1134. // 96 | PRC Envelope #1 (102 mm x 165 mm)
  1135. // 97 | PRC Envelope #2 (102 mm x 176 mm)
  1136. // 98 | PRC Envelope #3 (125 mm x 176 mm)
  1137. // 99 | PRC Envelope #4 (110 mm x 208 mm)
  1138. // 100 | PRC Envelope #5 (110 mm x 220 mm)
  1139. // 101 | PRC Envelope #6 (120 mm x 230 mm)
  1140. // 102 | PRC Envelope #7 (160 mm x 230 mm)
  1141. // 103 | PRC Envelope #8 (120 mm x 309 mm)
  1142. // 104 | PRC Envelope #9 (229 mm x 324 mm)
  1143. // 105 | PRC Envelope #10 (324 mm x 458 mm)
  1144. // 106 | PRC 16K Rotated
  1145. // 107 | PRC 32K Rotated
  1146. // 108 | PRC 32K(Big) Rotated
  1147. // 109 | PRC Envelope #1 Rotated (165 mm x 102 mm)
  1148. // 110 | PRC Envelope #2 Rotated (176 mm x 102 mm)
  1149. // 111 | PRC Envelope #3 Rotated (176 mm x 125 mm)
  1150. // 112 | PRC Envelope #4 Rotated (208 mm x 110 mm)
  1151. // 113 | PRC Envelope #5 Rotated (220 mm x 110 mm)
  1152. // 114 | PRC Envelope #6 Rotated (230 mm x 120 mm)
  1153. // 115 | PRC Envelope #7 Rotated (230 mm x 160 mm)
  1154. // 116 | PRC Envelope #8 Rotated (309 mm x 120 mm)
  1155. // 117 | PRC Envelope #9 Rotated (324 mm x 229 mm)
  1156. // 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
  1157. //
  1158. func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error {
  1159. s, err := f.workSheetReader(sheet)
  1160. if err != nil {
  1161. return err
  1162. }
  1163. ps := s.PageSetUp
  1164. if ps == nil {
  1165. ps = new(xlsxPageSetUp)
  1166. s.PageSetUp = ps
  1167. }
  1168. for _, opt := range opts {
  1169. opt.setPageLayout(ps)
  1170. }
  1171. return err
  1172. }
  1173. // GetPageLayout provides a function to gets worksheet page layout.
  1174. //
  1175. // Available options:
  1176. // PageLayoutOrientation(string)
  1177. // PageLayoutPaperSize(int)
  1178. // FitToHeight(int)
  1179. // FitToWidth(int)
  1180. func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error {
  1181. s, err := f.workSheetReader(sheet)
  1182. if err != nil {
  1183. return err
  1184. }
  1185. ps := s.PageSetUp
  1186. for _, opt := range opts {
  1187. opt.getPageLayout(ps)
  1188. }
  1189. return err
  1190. }
  1191. // SetDefinedName provides a function to set the defined names of the workbook
  1192. // or worksheet. If not specified scope, the default scope is workbook.
  1193. // For example:
  1194. //
  1195. // f.SetDefinedName(&excelize.DefinedName{
  1196. // Name: "Amount",
  1197. // RefersTo: "Sheet1!$A$2:$D$5",
  1198. // Comment: "defined name comment",
  1199. // Scope: "Sheet2",
  1200. // })
  1201. //
  1202. func (f *File) SetDefinedName(definedName *DefinedName) error {
  1203. wb := f.workbookReader()
  1204. d := xlsxDefinedName{
  1205. Name: definedName.Name,
  1206. Comment: definedName.Comment,
  1207. Data: definedName.RefersTo,
  1208. }
  1209. if definedName.Scope != "" {
  1210. if sheetID := f.GetSheetIndex(definedName.Scope); sheetID != 0 {
  1211. sheetID--
  1212. d.LocalSheetID = &sheetID
  1213. }
  1214. }
  1215. if wb.DefinedNames != nil {
  1216. for _, dn := range wb.DefinedNames.DefinedName {
  1217. var scope string
  1218. if dn.LocalSheetID != nil {
  1219. scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1220. }
  1221. if scope == definedName.Scope && dn.Name == definedName.Name {
  1222. return errors.New("the same name already exists on the scope")
  1223. }
  1224. }
  1225. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d)
  1226. return nil
  1227. }
  1228. wb.DefinedNames = &xlsxDefinedNames{
  1229. DefinedName: []xlsxDefinedName{d},
  1230. }
  1231. return nil
  1232. }
  1233. // DeleteDefinedName provides a function to delete the defined names of the
  1234. // workbook or worksheet. If not specified scope, the default scope is
  1235. // workbook. For example:
  1236. //
  1237. // f.DeleteDefinedName(&excelize.DefinedName{
  1238. // Name: "Amount",
  1239. // Scope: "Sheet2",
  1240. // })
  1241. //
  1242. func (f *File) DeleteDefinedName(definedName *DefinedName) error {
  1243. wb := f.workbookReader()
  1244. if wb.DefinedNames != nil {
  1245. for idx, dn := range wb.DefinedNames.DefinedName {
  1246. var scope string
  1247. if dn.LocalSheetID != nil {
  1248. scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1249. }
  1250. if scope == definedName.Scope && dn.Name == definedName.Name {
  1251. wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
  1252. return nil
  1253. }
  1254. }
  1255. }
  1256. return errors.New("no defined name on the scope")
  1257. }
  1258. // GetDefinedName provides a function to get the defined names of the workbook
  1259. // or worksheet.
  1260. func (f *File) GetDefinedName() []DefinedName {
  1261. var definedNames []DefinedName
  1262. wb := f.workbookReader()
  1263. if wb.DefinedNames != nil {
  1264. for _, dn := range wb.DefinedNames.DefinedName {
  1265. definedName := DefinedName{
  1266. Name: dn.Name,
  1267. Comment: dn.Comment,
  1268. RefersTo: dn.Data,
  1269. Scope: "Workbook",
  1270. }
  1271. if dn.LocalSheetID != nil {
  1272. definedName.Scope = f.GetSheetName(*dn.LocalSheetID + 1)
  1273. }
  1274. definedNames = append(definedNames, definedName)
  1275. }
  1276. }
  1277. return definedNames
  1278. }
  1279. // GroupSheets provides a function to group worksheets by given worksheets
  1280. // name. Group worksheets must contain an active worksheet.
  1281. func (f *File) GroupSheets(sheets []string) error {
  1282. // check an active worksheet in group worksheets
  1283. var inActiveSheet bool
  1284. activeSheet := f.GetActiveSheetIndex()
  1285. sheetMap := f.GetSheetMap()
  1286. for idx, sheetName := range sheetMap {
  1287. for _, s := range sheets {
  1288. if s == sheetName && idx == activeSheet {
  1289. inActiveSheet = true
  1290. }
  1291. }
  1292. }
  1293. if !inActiveSheet {
  1294. return errors.New("group worksheet must contain an active worksheet")
  1295. }
  1296. // check worksheet exists
  1297. ws := []*xlsxWorksheet{}
  1298. for _, sheet := range sheets {
  1299. xlsx, err := f.workSheetReader(sheet)
  1300. if err != nil {
  1301. return err
  1302. }
  1303. ws = append(ws, xlsx)
  1304. }
  1305. for _, s := range ws {
  1306. sheetViews := s.SheetViews.SheetView
  1307. if len(sheetViews) > 0 {
  1308. for idx := range sheetViews {
  1309. s.SheetViews.SheetView[idx].TabSelected = true
  1310. }
  1311. continue
  1312. }
  1313. }
  1314. return nil
  1315. }
  1316. // UngroupSheets provides a function to ungroup worksheets.
  1317. func (f *File) UngroupSheets() error {
  1318. activeSheet := f.GetActiveSheetIndex()
  1319. sheetMap := f.GetSheetMap()
  1320. for sheetID, sheet := range sheetMap {
  1321. if activeSheet == sheetID {
  1322. continue
  1323. }
  1324. xlsx, _ := f.workSheetReader(sheet)
  1325. sheetViews := xlsx.SheetViews.SheetView
  1326. if len(sheetViews) > 0 {
  1327. for idx := range sheetViews {
  1328. xlsx.SheetViews.SheetView[idx].TabSelected = false
  1329. }
  1330. }
  1331. }
  1332. return nil
  1333. }
  1334. // relsReader provides a function to get the pointer to the structure
  1335. // after deserialization of xl/worksheets/_rels/sheet%d.xml.rels.
  1336. func (f *File) relsReader(path string) *xlsxRelationships {
  1337. if f.Relationships[path] == nil {
  1338. _, ok := f.XLSX[path]
  1339. if ok {
  1340. c := xlsxRelationships{}
  1341. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &c)
  1342. f.Relationships[path] = &c
  1343. }
  1344. }
  1345. return f.Relationships[path]
  1346. }
  1347. // fillSheetData ensures there are enough rows, and columns in the chosen
  1348. // row to accept data. Missing rows are backfilled and given their row number
  1349. // Uses the last populated row as a hint for the size of the next row to add
  1350. func prepareSheetXML(xlsx *xlsxWorksheet, col int, row int) {
  1351. rowCount := len(xlsx.SheetData.Row)
  1352. sizeHint := 0
  1353. if rowCount > 0 {
  1354. sizeHint = len(xlsx.SheetData.Row[rowCount-1].C)
  1355. }
  1356. if rowCount < row {
  1357. // append missing rows
  1358. for rowIdx := rowCount; rowIdx < row; rowIdx++ {
  1359. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{R: rowIdx + 1, C: make([]xlsxC, 0, sizeHint)})
  1360. }
  1361. }
  1362. rowData := &xlsx.SheetData.Row[row-1]
  1363. fillColumns(rowData, col, row)
  1364. }
  1365. func fillColumns(rowData *xlsxRow, col, row int) {
  1366. cellCount := len(rowData.C)
  1367. if cellCount < col {
  1368. for colIdx := cellCount; colIdx < col; colIdx++ {
  1369. cellName, _ := CoordinatesToCellName(colIdx+1, row)
  1370. rowData.C = append(rowData.C, xlsxC{R: cellName})
  1371. }
  1372. }
  1373. }
  1374. func makeContiguousColumns(xlsx *xlsxWorksheet, fromRow, toRow, colCount int) {
  1375. for ; fromRow < toRow; fromRow++ {
  1376. rowData := &xlsx.SheetData.Row[fromRow-1]
  1377. fillColumns(rowData, colCount, fromRow)
  1378. }
  1379. }