sheet.go 49 KB

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