sheet.go 52 KB

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