excelize.go 10 KB

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