sheet.go 50 KB

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