sheet.go 62 KB

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