sheet.go 55 KB

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