sheet.go 50 KB

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