excelize.go 15 KB

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