sheet.go 49 KB

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