excelize.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package excelize
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "encoding/xml"
  6. "strconv"
  7. "strings"
  8. )
  9. // File define a populated xlsx.File struct.
  10. type File struct {
  11. XLSX map[string]string
  12. Path string
  13. SheetCount int
  14. }
  15. // OpenFile take the name of an XLSX file and returns a populated
  16. // xlsx.File struct for it.
  17. func OpenFile(filename string) (*File, error) {
  18. var f *zip.ReadCloser
  19. var err error
  20. file := make(map[string]string)
  21. sheetCount := 0
  22. f, err = zip.OpenReader(filename)
  23. if err != nil {
  24. return &File{}, err
  25. }
  26. file, sheetCount, _ = ReadZip(f)
  27. return &File{
  28. XLSX: file,
  29. Path: filename,
  30. SheetCount: sheetCount,
  31. }, nil
  32. }
  33. // SetCellValue provide function to set int or string type value of a cell.
  34. func (f *File) SetCellValue(sheet string, axis string, value interface{}) {
  35. switch t := value.(type) {
  36. case int, int8, int16, int32, int64, float32, float64:
  37. f.SetCellInt(sheet, axis, value.(int))
  38. case string:
  39. f.SetCellStr(sheet, axis, t)
  40. case []byte:
  41. f.SetCellStr(sheet, axis, string(t))
  42. default:
  43. f.SetCellStr(sheet, axis, ``)
  44. }
  45. }
  46. // SetCellInt provide function to set int type value of a cell.
  47. func (f *File) SetCellInt(sheet string, axis string, value int) {
  48. axis = strings.ToUpper(axis)
  49. var xlsx xlsxWorksheet
  50. col := string(strings.Map(letterOnlyMapF, axis))
  51. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  52. xAxis := row - 1
  53. yAxis := titleToNumber(col)
  54. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  55. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  56. rows := xAxis + 1
  57. cell := yAxis + 1
  58. xlsx = completeRow(xlsx, rows, cell)
  59. xlsx = completeCol(xlsx, rows, cell)
  60. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  61. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  62. output, _ := xml.Marshal(xlsx)
  63. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  64. }
  65. // SetCellStr provide function to set string type value of a cell.
  66. func (f *File) SetCellStr(sheet string, axis string, value string) {
  67. axis = strings.ToUpper(axis)
  68. var xlsx xlsxWorksheet
  69. col := string(strings.Map(letterOnlyMapF, axis))
  70. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  71. xAxis := row - 1
  72. yAxis := titleToNumber(col)
  73. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  74. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  75. rows := xAxis + 1
  76. cell := yAxis + 1
  77. xlsx = completeRow(xlsx, rows, cell)
  78. xlsx = completeCol(xlsx, rows, cell)
  79. xlsx.SheetData.Row[xAxis].C[yAxis].T = `str`
  80. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  81. output, _ := xml.Marshal(xlsx)
  82. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  83. }
  84. // Completion column element tags of XML in a sheet.
  85. func completeCol(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  86. if len(xlsx.SheetData.Row) < cell {
  87. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  88. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  89. R: i + 1,
  90. })
  91. }
  92. }
  93. buffer := bytes.Buffer{}
  94. for k, v := range xlsx.SheetData.Row {
  95. if len(v.C) < cell {
  96. start := len(v.C)
  97. for iii := start; iii < cell; iii++ {
  98. buffer.WriteString(toAlphaString(iii + 1))
  99. buffer.WriteString(strconv.Itoa(k + 1))
  100. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  101. R: buffer.String(),
  102. })
  103. buffer.Reset()
  104. }
  105. }
  106. }
  107. return xlsx
  108. }
  109. // Completion row element tags of XML in a sheet.
  110. func completeRow(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  111. if len(xlsx.SheetData.Row) < row {
  112. for i := len(xlsx.SheetData.Row); i < row; i++ {
  113. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  114. R: i + 1,
  115. })
  116. }
  117. buffer := bytes.Buffer{}
  118. for ii := 0; ii < row; ii++ {
  119. start := len(xlsx.SheetData.Row[ii].C)
  120. if start == 0 {
  121. for iii := start; iii < cell; iii++ {
  122. buffer.WriteString(toAlphaString(iii + 1))
  123. buffer.WriteString(strconv.Itoa(ii + 1))
  124. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  125. R: buffer.String(),
  126. })
  127. buffer.Reset()
  128. }
  129. }
  130. }
  131. }
  132. return xlsx
  133. }
  134. // Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Office Excel 2007.
  135. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  136. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  137. newXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">`
  138. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  139. workbookMarshal = strings.Replace(workbookMarshal, `></sheetPr>`, ` />`, -1)
  140. workbookMarshal = strings.Replace(workbookMarshal, `></dimension>`, ` />`, -1)
  141. workbookMarshal = strings.Replace(workbookMarshal, `></selection>`, ` />`, -1)
  142. workbookMarshal = strings.Replace(workbookMarshal, `></sheetFormatPr>`, ` />`, -1)
  143. workbookMarshal = strings.Replace(workbookMarshal, `></printOptions>`, ` />`, -1)
  144. workbookMarshal = strings.Replace(workbookMarshal, `></pageSetup>`, ` />`, -1)
  145. workbookMarshal = strings.Replace(workbookMarshal, `></pageMargins>`, ` />`, -1)
  146. workbookMarshal = strings.Replace(workbookMarshal, `></headerFooter>`, ` />`, -1)
  147. workbookMarshal = strings.Replace(workbookMarshal, `></drawing>`, ` />`, -1)
  148. return workbookMarshal
  149. }
  150. // Check XML tags and fix discontinuous case, for example:
  151. //
  152. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  153. // <c r="A15" s="2" />
  154. // <c r="B15" s="2" />
  155. // <c r="F15" s="1" />
  156. // <c r="G15" s="1" />
  157. // </row>
  158. //
  159. // in this case, we should to change it to
  160. //
  161. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  162. // <c r="A15" s="2" />
  163. // <c r="B15" s="2" />
  164. // <c r="C15" s="2" />
  165. // <c r="D15" s="2" />
  166. // <c r="E15" s="2" />
  167. // <c r="F15" s="1" />
  168. // <c r="G15" s="1" />
  169. // </row>
  170. //
  171. // Noteice: this method could be very slow for large spreadsheets (more than 3000 rows one sheet).
  172. func checkRow(xlsx xlsxWorksheet) xlsxWorksheet {
  173. buffer := bytes.Buffer{}
  174. for k, v := range xlsx.SheetData.Row {
  175. lenCol := len(v.C)
  176. if lenCol < 1 {
  177. continue
  178. }
  179. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  180. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  181. endCol := titleToNumber(endR) + 1
  182. if lenCol < endCol {
  183. oldRow := xlsx.SheetData.Row[k].C
  184. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  185. tmp := []xlsxC{}
  186. for i := 0; i <= endCol; i++ {
  187. buffer.WriteString(toAlphaString(i + 1))
  188. buffer.WriteString(strconv.Itoa(endRow))
  189. tmp = append(tmp, xlsxC{
  190. R: buffer.String(),
  191. })
  192. buffer.Reset()
  193. }
  194. xlsx.SheetData.Row[k].C = tmp
  195. for _, y := range oldRow {
  196. colAxis := titleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  197. xlsx.SheetData.Row[k].C[colAxis] = y
  198. }
  199. }
  200. }
  201. return xlsx
  202. }
  203. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  204. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  205. // cell have a linked value. Reference https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  206. //
  207. // Notice: after open XLSX file Excel will be update linked value and generate
  208. // new value and will prompt save file or not.
  209. //
  210. // For example:
  211. //
  212. // <row r="19" spans="2:2">
  213. // <c r="B19">
  214. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  215. // <v>100</v>
  216. // </c>
  217. // </row>
  218. //
  219. // to
  220. //
  221. // <row r="19" spans="2:2">
  222. // <c r="B19">
  223. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  224. // </c>
  225. // </row>
  226. func (f *File) UpdateLinkedValue() {
  227. for i := 1; i <= f.SheetCount; i++ {
  228. var xlsx xlsxWorksheet
  229. name := `xl/worksheets/sheet` + strconv.Itoa(i) + `.xml`
  230. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  231. for indexR, row := range xlsx.SheetData.Row {
  232. for indexC, col := range row.C {
  233. if col.F != nil && col.V != `` {
  234. xlsx.SheetData.Row[indexR].C[indexC].V = ``
  235. xlsx.SheetData.Row[indexR].C[indexC].T = ``
  236. }
  237. }
  238. }
  239. output, _ := xml.Marshal(xlsx)
  240. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  241. }
  242. }