sheet.go 50 KB

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