sheet.go 59 KB

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