sheet.go 53 KB

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