excelize.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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:
  37. f.SetCellInt(sheet, axis, value.(int))
  38. case int8:
  39. f.SetCellInt(sheet, axis, int(value.(int8)))
  40. case int16:
  41. f.SetCellInt(sheet, axis, int(value.(int16)))
  42. case int32:
  43. f.SetCellInt(sheet, axis, int(value.(int32)))
  44. case int64:
  45. f.SetCellInt(sheet, axis, int(value.(int64)))
  46. case float32:
  47. f.SetCellInt(sheet, axis, int(value.(float32)))
  48. case float64:
  49. f.SetCellInt(sheet, axis, int(value.(float64)))
  50. case string:
  51. f.SetCellStr(sheet, axis, t)
  52. case []byte:
  53. f.SetCellStr(sheet, axis, string(t))
  54. default:
  55. f.SetCellStr(sheet, axis, ``)
  56. }
  57. }
  58. // SetCellInt provide function to set int type value of a cell.
  59. func (f *File) SetCellInt(sheet string, axis string, value int) {
  60. axis = strings.ToUpper(axis)
  61. var xlsx xlsxWorksheet
  62. col := string(strings.Map(letterOnlyMapF, axis))
  63. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  64. xAxis := row - 1
  65. yAxis := titleToNumber(col)
  66. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  67. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  68. rows := xAxis + 1
  69. cell := yAxis + 1
  70. xlsx = completeRow(xlsx, rows, cell)
  71. xlsx = completeCol(xlsx, rows, cell)
  72. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  73. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  74. output, _ := xml.Marshal(xlsx)
  75. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  76. }
  77. // SetCellStr provide function to set string type value of a cell.
  78. func (f *File) SetCellStr(sheet string, axis string, value string) {
  79. axis = strings.ToUpper(axis)
  80. var xlsx xlsxWorksheet
  81. col := string(strings.Map(letterOnlyMapF, axis))
  82. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  83. xAxis := row - 1
  84. yAxis := titleToNumber(col)
  85. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  86. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  87. rows := xAxis + 1
  88. cell := yAxis + 1
  89. xlsx = completeRow(xlsx, rows, cell)
  90. xlsx = completeCol(xlsx, rows, cell)
  91. xlsx.SheetData.Row[xAxis].C[yAxis].T = `str`
  92. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  93. output, _ := xml.Marshal(xlsx)
  94. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  95. }
  96. // Completion column element tags of XML in a sheet.
  97. func completeCol(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  98. if len(xlsx.SheetData.Row) < cell {
  99. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  100. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  101. R: i + 1,
  102. })
  103. }
  104. }
  105. buffer := bytes.Buffer{}
  106. for k, v := range xlsx.SheetData.Row {
  107. if len(v.C) < cell {
  108. start := len(v.C)
  109. for iii := start; iii < cell; iii++ {
  110. buffer.WriteString(toAlphaString(iii + 1))
  111. buffer.WriteString(strconv.Itoa(k + 1))
  112. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  113. R: buffer.String(),
  114. })
  115. buffer.Reset()
  116. }
  117. }
  118. }
  119. return xlsx
  120. }
  121. // Completion row element tags of XML in a sheet.
  122. func completeRow(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  123. currentRows := len(xlsx.SheetData.Row)
  124. if currentRows > 1 {
  125. lastRow := xlsx.SheetData.Row[currentRows-1].R
  126. if lastRow >= row {
  127. row = lastRow
  128. }
  129. }
  130. sheetData := xlsxSheetData{}
  131. existsRows := map[int]int{}
  132. for k, v := range xlsx.SheetData.Row {
  133. existsRows[v.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. continue
  140. }
  141. sheetData.Row = append(sheetData.Row, xlsxRow{
  142. R: i + 1,
  143. })
  144. }
  145. buffer := bytes.Buffer{}
  146. for ii := 0; ii < row; ii++ {
  147. start := len(sheetData.Row[ii].C)
  148. if start == 0 {
  149. for iii := start; iii < cell; iii++ {
  150. buffer.WriteString(toAlphaString(iii + 1))
  151. buffer.WriteString(strconv.Itoa(ii + 1))
  152. sheetData.Row[ii].C = append(sheetData.Row[ii].C, xlsxC{
  153. R: buffer.String(),
  154. })
  155. buffer.Reset()
  156. }
  157. }
  158. }
  159. xlsx.SheetData = sheetData
  160. return xlsx
  161. }
  162. // Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Office Excel 2007.
  163. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  164. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  165. 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">`
  166. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  167. return workbookMarshal
  168. }
  169. // Check XML tags and fix discontinuous case, for example:
  170. //
  171. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  172. // <c r="A15" s="2" />
  173. // <c r="B15" s="2" />
  174. // <c r="F15" s="1" />
  175. // <c r="G15" s="1" />
  176. // </row>
  177. //
  178. // in this case, we should to change it to
  179. //
  180. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  181. // <c r="A15" s="2" />
  182. // <c r="B15" s="2" />
  183. // <c r="C15" s="2" />
  184. // <c r="D15" s="2" />
  185. // <c r="E15" s="2" />
  186. // <c r="F15" s="1" />
  187. // <c r="G15" s="1" />
  188. // </row>
  189. //
  190. // Noteice: this method could be very slow for large spreadsheets (more than 3000 rows one sheet).
  191. func checkRow(xlsx xlsxWorksheet) xlsxWorksheet {
  192. buffer := bytes.Buffer{}
  193. for k, v := range xlsx.SheetData.Row {
  194. lenCol := len(v.C)
  195. if lenCol < 1 {
  196. continue
  197. }
  198. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  199. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  200. endCol := titleToNumber(endR) + 1
  201. if lenCol < endCol {
  202. oldRow := xlsx.SheetData.Row[k].C
  203. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  204. tmp := []xlsxC{}
  205. for i := 0; i <= endCol; i++ {
  206. buffer.WriteString(toAlphaString(i + 1))
  207. buffer.WriteString(strconv.Itoa(endRow))
  208. tmp = append(tmp, xlsxC{
  209. R: buffer.String(),
  210. })
  211. buffer.Reset()
  212. }
  213. xlsx.SheetData.Row[k].C = tmp
  214. for _, y := range oldRow {
  215. colAxis := titleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  216. xlsx.SheetData.Row[k].C[colAxis] = y
  217. }
  218. }
  219. }
  220. return xlsx
  221. }
  222. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  223. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  224. // 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
  225. //
  226. // Notice: after open XLSX file Excel will be update linked value and generate
  227. // new value and will prompt save file or not.
  228. //
  229. // For example:
  230. //
  231. // <row r="19" spans="2:2">
  232. // <c r="B19">
  233. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  234. // <v>100</v>
  235. // </c>
  236. // </row>
  237. //
  238. // to
  239. //
  240. // <row r="19" spans="2:2">
  241. // <c r="B19">
  242. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  243. // </c>
  244. // </row>
  245. func (f *File) UpdateLinkedValue() {
  246. for i := 1; i <= f.SheetCount; i++ {
  247. var xlsx xlsxWorksheet
  248. name := `xl/worksheets/sheet` + strconv.Itoa(i) + `.xml`
  249. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  250. for indexR, row := range xlsx.SheetData.Row {
  251. for indexC, col := range row.C {
  252. if col.F != nil && col.V != `` {
  253. xlsx.SheetData.Row[indexR].C[indexC].V = ``
  254. xlsx.SheetData.Row[indexR].C[indexC].T = ``
  255. }
  256. }
  257. }
  258. output, _ := xml.Marshal(xlsx)
  259. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  260. }
  261. }