sheet.go 54 KB

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