excelize.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. WorkSheetRels map[string]*xlsxWorkbookRels
  41. XLSX map[string][]byte
  42. }
  43. // OpenFile take the name of an XLSX file and returns a populated XLSX file
  44. // struct for it.
  45. func OpenFile(filename string) (*File, error) {
  46. file, err := os.Open(filename)
  47. if err != nil {
  48. return nil, err
  49. }
  50. defer file.Close()
  51. f, err := OpenReader(file)
  52. if err != nil {
  53. return nil, err
  54. }
  55. f.Path = filename
  56. return f, nil
  57. }
  58. // OpenReader take an io.Reader and return a populated XLSX file.
  59. func OpenReader(r io.Reader) (*File, error) {
  60. b, err := ioutil.ReadAll(r)
  61. if err != nil {
  62. return nil, err
  63. }
  64. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  65. if err != nil {
  66. return nil, err
  67. }
  68. file, sheetCount, err := ReadZipReader(zr)
  69. if err != nil {
  70. return nil, err
  71. }
  72. f := &File{
  73. checked: make(map[string]bool),
  74. Comments: make(map[string]*xlsxComments),
  75. DrawingRels: make(map[string]*xlsxWorkbookRels),
  76. Drawings: make(map[string]*xlsxWsDr),
  77. Sheet: make(map[string]*xlsxWorksheet),
  78. SheetCount: sheetCount,
  79. DecodeVMLDrawing: make(map[string]*decodeVmlDrawing),
  80. VMLDrawing: make(map[string]*vmlDrawing),
  81. WorkSheetRels: make(map[string]*xlsxWorkbookRels),
  82. XLSX: file,
  83. }
  84. f.CalcChain = f.calcChainReader()
  85. f.sheetMap = f.getSheetMap()
  86. f.Styles = f.stylesReader()
  87. f.Theme = f.themeReader()
  88. return f, nil
  89. }
  90. // setDefaultTimeStyle provides a function to set default numbers format for
  91. // time.Time type cell value by given worksheet name, cell coordinates and
  92. // number format code.
  93. func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
  94. if f.GetCellStyle(sheet, axis) == 0 {
  95. style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`)
  96. f.SetCellStyle(sheet, axis, axis, style)
  97. }
  98. }
  99. // workSheetReader provides a function to get the pointer to the structure
  100. // after deserialization by given worksheet name.
  101. func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
  102. name, ok := f.sheetMap[trimSheetName(sheet)]
  103. if !ok {
  104. name = "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  105. }
  106. if f.Sheet[name] == nil {
  107. var xlsx xlsxWorksheet
  108. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(name)), &xlsx)
  109. if f.checked == nil {
  110. f.checked = make(map[string]bool)
  111. }
  112. ok := f.checked[name]
  113. if !ok {
  114. checkSheet(&xlsx)
  115. checkRow(&xlsx)
  116. f.checked[name] = true
  117. }
  118. f.Sheet[name] = &xlsx
  119. }
  120. return f.Sheet[name]
  121. }
  122. // checkSheet provides a function to fill each row element and make that is
  123. // continuous in a worksheet of XML.
  124. func checkSheet(xlsx *xlsxWorksheet) {
  125. row := len(xlsx.SheetData.Row)
  126. if row >= 1 {
  127. lastRow := xlsx.SheetData.Row[row-1].R
  128. if lastRow >= row {
  129. row = lastRow
  130. }
  131. }
  132. sheetData := xlsxSheetData{}
  133. existsRows := map[int]int{}
  134. for k := range xlsx.SheetData.Row {
  135. existsRows[xlsx.SheetData.Row[k].R] = k
  136. }
  137. for i := 0; i < row; i++ {
  138. _, ok := existsRows[i+1]
  139. if ok {
  140. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  141. } else {
  142. sheetData.Row = append(sheetData.Row, xlsxRow{
  143. R: i + 1,
  144. })
  145. }
  146. }
  147. xlsx.SheetData = sheetData
  148. }
  149. // replaceWorkSheetsRelationshipsNameSpaceBytes provides a function to replace
  150. // xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
  151. // Office Excel 2007.
  152. func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  153. var oldXmlns = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  154. 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">`)
  155. workbookMarshal = bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  156. return workbookMarshal
  157. }
  158. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  159. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  160. // cell have a linked value. Reference
  161. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating
  162. //
  163. // Notice: after open XLSX file Excel will be update linked value and generate
  164. // new value and will prompt save file or not.
  165. //
  166. // For example:
  167. //
  168. // <row r="19" spans="2:2">
  169. // <c r="B19">
  170. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  171. // <v>100</v>
  172. // </c>
  173. // </row>
  174. //
  175. // to
  176. //
  177. // <row r="19" spans="2:2">
  178. // <c r="B19">
  179. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  180. // </c>
  181. // </row>
  182. //
  183. func (f *File) UpdateLinkedValue() {
  184. for _, name := range f.GetSheetMap() {
  185. xlsx := f.workSheetReader(name)
  186. for indexR := range xlsx.SheetData.Row {
  187. for indexC, col := range xlsx.SheetData.Row[indexR].C {
  188. if col.F != nil && col.V != "" {
  189. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  190. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  191. }
  192. }
  193. }
  194. }
  195. }
  196. // GetMergeCells provides a function to get all merged cells from a worksheet currently.
  197. func (f *File) GetMergeCells(sheet string) []MergeCell {
  198. xlsx := f.workSheetReader(sheet)
  199. var mergeCells []MergeCell
  200. if xlsx.MergeCells != nil {
  201. mergeCells = make([]MergeCell, 0, len(xlsx.MergeCells.Cells))
  202. for i := range xlsx.MergeCells.Cells {
  203. ref := xlsx.MergeCells.Cells[i].Ref
  204. axis := strings.Split(ref, ":")[0]
  205. mergeCells = append(mergeCells, []string{ref, f.GetCellValue(sheet, axis)})
  206. }
  207. }
  208. return mergeCells
  209. }
  210. // MergeCell define a merged cell data.
  211. // It consists of the following structure.
  212. // example: []string{"D4:E10", "cell value"}
  213. type MergeCell []string
  214. // GetCellValue returns merged cell value.
  215. func (m *MergeCell) GetCellValue() string {
  216. return (*m)[1]
  217. }
  218. // GetStartAxis returns the merge start axis.
  219. // example: "C2"
  220. func (m *MergeCell) GetStartAxis() string {
  221. axis := strings.Split((*m)[0], ":")
  222. return axis[0]
  223. }
  224. // GetEndAxis returns the merge end axis.
  225. // example: "D4"
  226. func (m *MergeCell) GetEndAxis() string {
  227. axis := strings.Split((*m)[0], ":")
  228. return axis[1]
  229. }