excelize.go 8.1 KB

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