sheet.go 54 KB

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