excelize.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // Copyright 2016 - 2019 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. // Package excelize providing a set of functions that allow you to write to
  5. // and read from XLSX files. Support reads and writes XLSX file generated by
  6. // Microsoft Excel™ 2007 and later. Support save file without losing original
  7. // charts of XLSX. This library needs Go version 1.8 or later.
  8. //
  9. // See https://xuri.me/excelize for more information about this package.
  10. package excelize
  11. import (
  12. "archive/zip"
  13. "bytes"
  14. "encoding/xml"
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "strconv"
  19. "strings"
  20. )
  21. // File define a populated XLSX file struct.
  22. type File struct {
  23. checked map[string]bool
  24. sheetMap map[string]string
  25. CalcChain *xlsxCalcChain
  26. Comments map[string]*xlsxComments
  27. ContentTypes *xlsxTypes
  28. DrawingRels map[string]*xlsxWorkbookRels
  29. Drawings map[string]*xlsxWsDr
  30. Path string
  31. SharedStrings *xlsxSST
  32. Sheet map[string]*xlsxWorksheet
  33. SheetCount int
  34. Styles *xlsxStyleSheet
  35. Theme *xlsxTheme
  36. DecodeVMLDrawing map[string]*decodeVmlDrawing
  37. VMLDrawing map[string]*vmlDrawing
  38. WorkBook *xlsxWorkbook
  39. WorkBookRels *xlsxWorkbookRels
  40. XLSX map[string][]byte
  41. }
  42. // OpenFile take the name of an XLSX file and returns a populated XLSX file
  43. // struct for it.
  44. func OpenFile(filename string) (*File, error) {
  45. file, err := os.Open(filename)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer file.Close()
  50. f, err := OpenReader(file)
  51. if err != nil {
  52. return nil, err
  53. }
  54. f.Path = filename
  55. return f, nil
  56. }
  57. // OpenReader take an io.Reader and return a populated XLSX file.
  58. func OpenReader(r io.Reader) (*File, error) {
  59. b, err := ioutil.ReadAll(r)
  60. if err != nil {
  61. return nil, err
  62. }
  63. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  64. if err != nil {
  65. return nil, err
  66. }
  67. file, sheetCount, err := ReadZipReader(zr)
  68. if err != nil {
  69. return nil, err
  70. }
  71. f := &File{
  72. checked: make(map[string]bool),
  73. Comments: make(map[string]*xlsxComments),
  74. DrawingRels: make(map[string]*xlsxWorkbookRels),
  75. Drawings: make(map[string]*xlsxWsDr),
  76. Sheet: make(map[string]*xlsxWorksheet),
  77. SheetCount: sheetCount,
  78. DecodeVMLDrawing: make(map[string]*decodeVmlDrawing),
  79. VMLDrawing: make(map[string]*vmlDrawing),
  80. XLSX: file,
  81. }
  82. f.CalcChain = f.calcChainReader()
  83. f.sheetMap = f.getSheetMap()
  84. f.Styles = f.stylesReader()
  85. f.Theme = f.themeReader()
  86. return f, nil
  87. }
  88. // setDefaultTimeStyle provides a function to set default numbers format for
  89. // time.Time type cell value by given worksheet name, cell coordinates and
  90. // number format code.
  91. func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
  92. if f.GetCellStyle(sheet, axis) == 0 {
  93. style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`)
  94. f.SetCellStyle(sheet, axis, axis, style)
  95. }
  96. }
  97. // workSheetReader provides a function to get the pointer to the structure
  98. // after deserialization by given worksheet name.
  99. func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
  100. name, ok := f.sheetMap[trimSheetName(sheet)]
  101. if !ok {
  102. name = "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  103. }
  104. if f.Sheet[name] == nil {
  105. var xlsx xlsxWorksheet
  106. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(name)), &xlsx)
  107. if f.checked == nil {
  108. f.checked = make(map[string]bool)
  109. }
  110. ok := f.checked[name]
  111. if !ok {
  112. checkSheet(&xlsx)
  113. checkRow(&xlsx)
  114. f.checked[name] = true
  115. }
  116. f.Sheet[name] = &xlsx
  117. }
  118. return f.Sheet[name]
  119. }
  120. // checkSheet provides a function to fill each row element and make that is
  121. // continuous in a worksheet of XML.
  122. func checkSheet(xlsx *xlsxWorksheet) {
  123. row := len(xlsx.SheetData.Row)
  124. if row >= 1 {
  125. lastRow := xlsx.SheetData.Row[row-1].R
  126. if lastRow >= row {
  127. row = lastRow
  128. }
  129. }
  130. sheetData := xlsxSheetData{}
  131. existsRows := map[int]int{}
  132. for k := range xlsx.SheetData.Row {
  133. existsRows[xlsx.SheetData.Row[k].R] = k
  134. }
  135. for i := 0; i < row; i++ {
  136. _, ok := existsRows[i+1]
  137. if ok {
  138. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  139. } else {
  140. sheetData.Row = append(sheetData.Row, xlsxRow{
  141. R: i + 1,
  142. })
  143. }
  144. }
  145. xlsx.SheetData = sheetData
  146. }
  147. // replaceWorkSheetsRelationshipsNameSpaceBytes provides a function to replace
  148. // xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
  149. // Office Excel 2007.
  150. func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  151. var oldXmlns = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  152. var newXmlns = []byte(`<worksheet xr:uid="{00000000-0001-0000-0000-000000000000}" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac xr xr2 xr3" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  153. workbookMarshal = bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  154. return workbookMarshal
  155. }
  156. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  157. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  158. // cell have a linked value. Reference
  159. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating
  160. //
  161. // Notice: after open XLSX file Excel will be update linked value and generate
  162. // new value and will prompt save file or not.
  163. //
  164. // For example:
  165. //
  166. // <row r="19" spans="2:2">
  167. // <c r="B19">
  168. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  169. // <v>100</v>
  170. // </c>
  171. // </row>
  172. //
  173. // to
  174. //
  175. // <row r="19" spans="2:2">
  176. // <c r="B19">
  177. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  178. // </c>
  179. // </row>
  180. //
  181. func (f *File) UpdateLinkedValue() {
  182. for _, name := range f.GetSheetMap() {
  183. xlsx := f.workSheetReader(name)
  184. for indexR := range xlsx.SheetData.Row {
  185. for indexC, col := range xlsx.SheetData.Row[indexR].C {
  186. if col.F != nil && col.V != "" {
  187. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  188. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  189. }
  190. }
  191. }
  192. }
  193. }
  194. // adjustHelper provides a function to adjust rows and columns dimensions,
  195. // hyperlinks, merged cells and auto filter when inserting or deleting rows or
  196. // columns.
  197. //
  198. // sheet: Worksheet name that we're editing
  199. // column: Index number of the column we're inserting/deleting before
  200. // row: Index number of the row we're inserting/deleting before
  201. // offset: Number of rows/column to insert/delete negative values indicate deletion
  202. //
  203. // TODO: adjustCalcChain, adjustPageBreaks, adjustComments,
  204. // adjustDataValidations, adjustProtectedCells
  205. //
  206. func (f *File) adjustHelper(sheet string, column, row, offset int) {
  207. xlsx := f.workSheetReader(sheet)
  208. f.adjustRowDimensions(xlsx, row, offset)
  209. f.adjustColDimensions(xlsx, column, offset)
  210. f.adjustHyperlinks(sheet, column, row, offset)
  211. f.adjustMergeCells(xlsx, column, row, offset)
  212. f.adjustAutoFilter(xlsx, column, row, offset)
  213. checkSheet(xlsx)
  214. checkRow(xlsx)
  215. }
  216. // adjustColDimensions provides a function to update column dimensions when
  217. // inserting or deleting rows or columns.
  218. func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
  219. for i, r := range xlsx.SheetData.Row {
  220. for k, v := range r.C {
  221. axis := v.R
  222. col := string(strings.Map(letterOnlyMapF, axis))
  223. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  224. yAxis := TitleToNumber(col)
  225. if yAxis >= column && column != -1 {
  226. xlsx.SheetData.Row[i].C[k].R = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  227. }
  228. }
  229. }
  230. }
  231. // adjustRowDimensions provides a function to update row dimensions when
  232. // inserting or deleting rows or columns.
  233. func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
  234. if rowIndex == -1 {
  235. return
  236. }
  237. for i, r := range xlsx.SheetData.Row {
  238. if r.R >= rowIndex {
  239. f.ajustSingleRowDimensions(&xlsx.SheetData.Row[i], r.R+offset)
  240. }
  241. }
  242. }
  243. // ajustSingleRowDimensions provides a function to ajust single row dimensions.
  244. func (f *File) ajustSingleRowDimensions(r *xlsxRow, row int) {
  245. r.R = row
  246. for i, col := range r.C {
  247. r.C[i].R = string(strings.Map(letterOnlyMapF, col.R)) + strconv.Itoa(r.R)
  248. }
  249. }
  250. // adjustHyperlinks provides a function to update hyperlinks when inserting or
  251. // deleting rows or columns.
  252. func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
  253. xlsx := f.workSheetReader(sheet)
  254. // order is important
  255. if xlsx.Hyperlinks != nil && offset < 0 {
  256. for i, v := range xlsx.Hyperlinks.Hyperlink {
  257. axis := v.Ref
  258. col := string(strings.Map(letterOnlyMapF, axis))
  259. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  260. yAxis := TitleToNumber(col)
  261. if row == rowIndex || yAxis == column {
  262. f.deleteSheetRelationships(sheet, v.RID)
  263. if len(xlsx.Hyperlinks.Hyperlink) > 1 {
  264. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i], xlsx.Hyperlinks.Hyperlink[i+1:]...)
  265. } else {
  266. xlsx.Hyperlinks = nil
  267. }
  268. }
  269. }
  270. }
  271. if xlsx.Hyperlinks != nil {
  272. for i, v := range xlsx.Hyperlinks.Hyperlink {
  273. axis := v.Ref
  274. col := string(strings.Map(letterOnlyMapF, axis))
  275. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  276. xAxis := row + offset
  277. yAxis := TitleToNumber(col)
  278. if rowIndex != -1 && row >= rowIndex {
  279. xlsx.Hyperlinks.Hyperlink[i].Ref = col + strconv.Itoa(xAxis)
  280. }
  281. if column != -1 && yAxis >= column {
  282. xlsx.Hyperlinks.Hyperlink[i].Ref = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  283. }
  284. }
  285. }
  286. }
  287. // adjustMergeCellsHelper provides a function to update merged cells when
  288. // inserting or deleting rows or columns.
  289. func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  290. if xlsx.MergeCells != nil {
  291. for k, v := range xlsx.MergeCells.Cells {
  292. beg := strings.Split(v.Ref, ":")[0]
  293. end := strings.Split(v.Ref, ":")[1]
  294. begcol := string(strings.Map(letterOnlyMapF, beg))
  295. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  296. begxAxis := begrow + offset
  297. begyAxis := TitleToNumber(begcol)
  298. endcol := string(strings.Map(letterOnlyMapF, end))
  299. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  300. endxAxis := endrow + offset
  301. endyAxis := TitleToNumber(endcol)
  302. if rowIndex != -1 {
  303. if begrow > 1 && begrow >= rowIndex {
  304. beg = begcol + strconv.Itoa(begxAxis)
  305. }
  306. if endrow > 1 && endrow >= rowIndex {
  307. end = endcol + strconv.Itoa(endxAxis)
  308. }
  309. }
  310. if column != -1 {
  311. if begyAxis >= column {
  312. beg = ToAlphaString(begyAxis+offset) + strconv.Itoa(endrow)
  313. }
  314. if endyAxis >= column {
  315. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  316. }
  317. }
  318. xlsx.MergeCells.Cells[k].Ref = beg + ":" + end
  319. }
  320. }
  321. }
  322. // adjustMergeCells provides a function to update merged cells when inserting
  323. // or deleting rows or columns.
  324. func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  325. f.adjustMergeCellsHelper(xlsx, column, rowIndex, offset)
  326. if xlsx.MergeCells != nil && offset < 0 {
  327. for k, v := range xlsx.MergeCells.Cells {
  328. beg := strings.Split(v.Ref, ":")[0]
  329. end := strings.Split(v.Ref, ":")[1]
  330. if beg == end {
  331. xlsx.MergeCells.Count += offset
  332. if len(xlsx.MergeCells.Cells) > 1 {
  333. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:k], xlsx.MergeCells.Cells[k+1:]...)
  334. } else {
  335. xlsx.MergeCells = nil
  336. }
  337. }
  338. }
  339. }
  340. }
  341. // adjustAutoFilter provides a function to update the auto filter when
  342. // inserting or deleting rows or columns.
  343. func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  344. f.adjustAutoFilterHelper(xlsx, column, rowIndex, offset)
  345. if xlsx.AutoFilter != nil {
  346. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  347. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  348. begcol := string(strings.Map(letterOnlyMapF, beg))
  349. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  350. begxAxis := begrow + offset
  351. endcol := string(strings.Map(letterOnlyMapF, end))
  352. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  353. endxAxis := endrow + offset
  354. endyAxis := TitleToNumber(endcol)
  355. if rowIndex != -1 {
  356. if begrow >= rowIndex {
  357. beg = begcol + strconv.Itoa(begxAxis)
  358. }
  359. if endrow >= rowIndex {
  360. end = endcol + strconv.Itoa(endxAxis)
  361. }
  362. }
  363. if column != -1 && endyAxis >= column {
  364. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  365. }
  366. xlsx.AutoFilter.Ref = beg + ":" + end
  367. }
  368. }
  369. // adjustAutoFilterHelper provides a function to update the auto filter when
  370. // inserting or deleting rows or columns.
  371. func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  372. if xlsx.AutoFilter != nil {
  373. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  374. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  375. begcol := string(strings.Map(letterOnlyMapF, beg))
  376. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  377. begyAxis := TitleToNumber(begcol)
  378. endcol := string(strings.Map(letterOnlyMapF, end))
  379. endyAxis := TitleToNumber(endcol)
  380. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  381. if (begrow == rowIndex && offset < 0) || (column == begyAxis && column == endyAxis) {
  382. xlsx.AutoFilter = nil
  383. for i, r := range xlsx.SheetData.Row {
  384. if begrow < r.R && r.R <= endrow {
  385. xlsx.SheetData.Row[i].Hidden = false
  386. }
  387. }
  388. }
  389. }
  390. }
  391. // GetMergeCells provides a function to get all merged cells from a worksheet currently.
  392. func (f *File) GetMergeCells(sheet string) []MergeCell {
  393. mergeCells := []MergeCell{}
  394. xlsx := f.workSheetReader(sheet)
  395. if xlsx.MergeCells != nil {
  396. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  397. ref := xlsx.MergeCells.Cells[i].Ref
  398. axis := strings.Split(ref, ":")[0]
  399. mergeCells = append(mergeCells, []string{ref, f.GetCellValue(sheet, axis)})
  400. }
  401. }
  402. return mergeCells
  403. }
  404. // MergeCell define a merged cell data.
  405. // It consists of the following structure.
  406. // example: []string{"D4:E10", "cell value"}
  407. type MergeCell []string
  408. // GetCellValue returns merged cell value.
  409. func (m *MergeCell) GetCellValue() string {
  410. return (*m)[1]
  411. }
  412. // GetStartAxis returns the merge start axis.
  413. // example: "C2"
  414. func (m *MergeCell) GetStartAxis() string {
  415. axis := strings.Split((*m)[0], ":")
  416. return axis[0]
  417. }
  418. // GetEndAxis returns the merge end axis.
  419. // example: "D4"
  420. func (m *MergeCell) GetEndAxis() string {
  421. axis := strings.Split((*m)[0], ":")
  422. return axis[1]
  423. }