excelize.go 9.4 KB

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