sheet.go 57 KB

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