excelize.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 XLSX file
  16. // 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 provides 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.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
  48. case float64:
  49. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
  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 provides 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, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  76. }
  77. // SetCellStr provides 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, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  95. }
  96. // SetCellDefault provides function to set string type value of a cell as
  97. // default format without escaping the cell.
  98. func (f *File) SetCellDefault(sheet string, axis string, value string) {
  99. axis = strings.ToUpper(axis)
  100. var xlsx xlsxWorksheet
  101. col := string(strings.Map(letterOnlyMapF, axis))
  102. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  103. xAxis := row - 1
  104. yAxis := titleToNumber(col)
  105. name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  106. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  107. rows := xAxis + 1
  108. cell := yAxis + 1
  109. xlsx = completeRow(xlsx, rows, cell)
  110. xlsx = completeCol(xlsx, rows, cell)
  111. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  112. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  113. output, _ := xml.Marshal(xlsx)
  114. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  115. }
  116. // Completion column element tags of XML in a sheet.
  117. func completeCol(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  118. if len(xlsx.SheetData.Row) < cell {
  119. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  120. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  121. R: i + 1,
  122. })
  123. }
  124. }
  125. buffer := bytes.Buffer{}
  126. for k, v := range xlsx.SheetData.Row {
  127. if len(v.C) < cell {
  128. start := len(v.C)
  129. for iii := start; iii < cell; iii++ {
  130. buffer.WriteString(toAlphaString(iii + 1))
  131. buffer.WriteString(strconv.Itoa(k + 1))
  132. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  133. R: buffer.String(),
  134. })
  135. buffer.Reset()
  136. }
  137. }
  138. }
  139. return xlsx
  140. }
  141. // Completion row element tags of XML in a sheet.
  142. func completeRow(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  143. currentRows := len(xlsx.SheetData.Row)
  144. if currentRows > 1 {
  145. lastRow := xlsx.SheetData.Row[currentRows-1].R
  146. if lastRow >= row {
  147. row = lastRow
  148. }
  149. }
  150. sheetData := xlsxSheetData{}
  151. existsRows := map[int]int{}
  152. for k, v := range xlsx.SheetData.Row {
  153. existsRows[v.R] = k
  154. }
  155. for i := 0; i < row; i++ {
  156. _, ok := existsRows[i+1]
  157. if ok {
  158. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  159. continue
  160. }
  161. sheetData.Row = append(sheetData.Row, xlsxRow{
  162. R: i + 1,
  163. })
  164. }
  165. buffer := bytes.Buffer{}
  166. for ii := 0; ii < row; ii++ {
  167. start := len(sheetData.Row[ii].C)
  168. if start == 0 {
  169. for iii := start; iii < cell; iii++ {
  170. buffer.WriteString(toAlphaString(iii + 1))
  171. buffer.WriteString(strconv.Itoa(ii + 1))
  172. sheetData.Row[ii].C = append(sheetData.Row[ii].C, xlsxC{
  173. R: buffer.String(),
  174. })
  175. buffer.Reset()
  176. }
  177. }
  178. }
  179. xlsx.SheetData = sheetData
  180. return xlsx
  181. }
  182. // Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible
  183. // Office Excel 2007.
  184. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  185. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  186. 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">`
  187. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  188. return workbookMarshal
  189. }
  190. // Check XML tags and fix discontinuous case. For example:
  191. //
  192. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  193. // <c r="A15" s="2" />
  194. // <c r="B15" s="2" />
  195. // <c r="F15" s="1" />
  196. // <c r="G15" s="1" />
  197. // </row>
  198. //
  199. // in this case, we should to change it to
  200. //
  201. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  202. // <c r="A15" s="2" />
  203. // <c r="B15" s="2" />
  204. // <c r="C15" s="2" />
  205. // <c r="D15" s="2" />
  206. // <c r="E15" s="2" />
  207. // <c r="F15" s="1" />
  208. // <c r="G15" s="1" />
  209. // </row>
  210. //
  211. // Noteice: this method could be very slow for large spreadsheets (more than
  212. // 3000 rows one sheet).
  213. func checkRow(xlsx xlsxWorksheet) xlsxWorksheet {
  214. buffer := bytes.Buffer{}
  215. for k, v := range xlsx.SheetData.Row {
  216. lenCol := len(v.C)
  217. if lenCol < 1 {
  218. continue
  219. }
  220. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  221. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  222. endCol := titleToNumber(endR) + 1
  223. if lenCol < endCol {
  224. oldRow := xlsx.SheetData.Row[k].C
  225. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  226. tmp := []xlsxC{}
  227. for i := 0; i <= endCol; i++ {
  228. buffer.WriteString(toAlphaString(i + 1))
  229. buffer.WriteString(strconv.Itoa(endRow))
  230. tmp = append(tmp, xlsxC{
  231. R: buffer.String(),
  232. })
  233. buffer.Reset()
  234. }
  235. xlsx.SheetData.Row[k].C = tmp
  236. for _, y := range oldRow {
  237. colAxis := titleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  238. xlsx.SheetData.Row[k].C[colAxis] = y
  239. }
  240. }
  241. }
  242. return xlsx
  243. }
  244. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  245. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  246. // cell have a linked value. Reference
  247. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  248. //
  249. // Notice: after open XLSX file Excel will be update linked value and generate
  250. // new value and will prompt save file or not.
  251. //
  252. // For example:
  253. //
  254. // <row r="19" spans="2:2">
  255. // <c r="B19">
  256. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  257. // <v>100</v>
  258. // </c>
  259. // </row>
  260. //
  261. // to
  262. //
  263. // <row r="19" spans="2:2">
  264. // <c r="B19">
  265. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  266. // </c>
  267. // </row>
  268. //
  269. func (f *File) UpdateLinkedValue() {
  270. for i := 1; i <= f.SheetCount; i++ {
  271. var xlsx xlsxWorksheet
  272. name := "xl/worksheets/sheet" + strconv.Itoa(i) + ".xml"
  273. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  274. for indexR, row := range xlsx.SheetData.Row {
  275. for indexC, col := range row.C {
  276. if col.F != nil && col.V != "" {
  277. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  278. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  279. }
  280. }
  281. }
  282. output, _ := xml.Marshal(xlsx)
  283. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  284. }
  285. }