excelize.go 9.2 KB

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