excelize.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package excelize
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "encoding/xml"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. )
  10. // File define a populated xlsx.File struct.
  11. type File struct {
  12. XLSX map[string]string
  13. Path string
  14. SheetCount int
  15. }
  16. // OpenFile take the name of an XLSX file and returns a populated
  17. // xlsx.File struct for it.
  18. func OpenFile(filename string) (*File, error) {
  19. var f *zip.ReadCloser
  20. var err error
  21. file := make(map[string]string)
  22. sheetCount := 0
  23. f, err = zip.OpenReader(filename)
  24. if err != nil {
  25. return &File{}, err
  26. }
  27. file, sheetCount, err = ReadZip(f)
  28. return &File{
  29. XLSX: file,
  30. Path: filename,
  31. SheetCount: sheetCount,
  32. }, nil
  33. }
  34. // SetCellInt provide function to set int type value of a cell
  35. func (f *File) SetCellInt(sheet string, axis string, value int) {
  36. axis = strings.ToUpper(axis)
  37. var xlsx xlsxWorksheet
  38. col := getColIndex(axis)
  39. row := getRowIndex(axis)
  40. xAxis := row - 1
  41. yAxis := titleToNumber(col)
  42. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  43. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  44. rows := xAxis + 1
  45. cell := yAxis + 1
  46. xlsx = checkRow(xlsx)
  47. xlsx = completeRow(xlsx, rows, cell)
  48. xlsx = completeCol(xlsx, rows, cell)
  49. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  50. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  51. output, err := xml.Marshal(xlsx)
  52. if err != nil {
  53. fmt.Println(err)
  54. }
  55. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  56. }
  57. // SetCellStr provide function to set string type value of a cell
  58. func (f *File) SetCellStr(sheet string, axis string, value string) {
  59. axis = strings.ToUpper(axis)
  60. var xlsx xlsxWorksheet
  61. col := getColIndex(axis)
  62. row := getRowIndex(axis)
  63. xAxis := row - 1
  64. yAxis := titleToNumber(col)
  65. name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
  66. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  67. rows := xAxis + 1
  68. cell := yAxis + 1
  69. xlsx = checkRow(xlsx)
  70. xlsx = completeRow(xlsx, rows, cell)
  71. xlsx = completeCol(xlsx, rows, cell)
  72. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  73. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  74. output, err := xml.Marshal(xlsx)
  75. if err != nil {
  76. fmt.Println(err)
  77. }
  78. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  79. }
  80. // Completion column element tags of XML in a sheet
  81. func completeCol(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  82. if len(xlsx.SheetData.Row) < cell {
  83. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  84. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  85. R: i + 1,
  86. })
  87. }
  88. }
  89. buffer := bytes.Buffer{}
  90. for k, v := range xlsx.SheetData.Row {
  91. if len(v.C) < cell {
  92. start := len(v.C)
  93. for iii := start; iii < cell; iii++ {
  94. buffer.WriteString(toAlphaString(iii + 1))
  95. buffer.WriteString(strconv.Itoa(k + 1))
  96. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  97. R: buffer.String(),
  98. })
  99. buffer.Reset()
  100. }
  101. }
  102. }
  103. return xlsx
  104. }
  105. // Completion row element tags of XML in a sheet
  106. func completeRow(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
  107. if len(xlsx.SheetData.Row) < row {
  108. for i := len(xlsx.SheetData.Row); i < row; i++ {
  109. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  110. R: i + 1,
  111. })
  112. }
  113. buffer := bytes.Buffer{}
  114. for ii := 0; ii < row; ii++ {
  115. start := len(xlsx.SheetData.Row[ii].C)
  116. if start == 0 {
  117. for iii := start; iii < cell; iii++ {
  118. buffer.WriteString(toAlphaString(iii + 1))
  119. buffer.WriteString(strconv.Itoa(ii + 1))
  120. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  121. R: buffer.String(),
  122. })
  123. buffer.Reset()
  124. }
  125. }
  126. }
  127. }
  128. return xlsx
  129. }
  130. // Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Office Excel 2007
  131. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  132. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  133. 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">`
  134. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  135. workbookMarshal = strings.Replace(workbookMarshal, `></sheetPr>`, ` />`, -1)
  136. workbookMarshal = strings.Replace(workbookMarshal, `></dimension>`, ` />`, -1)
  137. workbookMarshal = strings.Replace(workbookMarshal, `></selection>`, ` />`, -1)
  138. workbookMarshal = strings.Replace(workbookMarshal, `></sheetFormatPr>`, ` />`, -1)
  139. workbookMarshal = strings.Replace(workbookMarshal, `></printOptions>`, ` />`, -1)
  140. workbookMarshal = strings.Replace(workbookMarshal, `></pageSetup>`, ` />`, -1)
  141. workbookMarshal = strings.Replace(workbookMarshal, `></pageMargins>`, ` />`, -1)
  142. workbookMarshal = strings.Replace(workbookMarshal, `></headerFooter>`, ` />`, -1)
  143. workbookMarshal = strings.Replace(workbookMarshal, `></drawing>`, ` />`, -1)
  144. return workbookMarshal
  145. }
  146. // Check XML tags and fix discontinuous case, for example:
  147. //
  148. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  149. // <c r="A15" s="2" />
  150. // <c r="B15" s="2" />
  151. // <c r="F15" s="1" />
  152. // <c r="G15" s="1" />
  153. // </row>
  154. //
  155. // in this case, we should to change it to
  156. //
  157. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  158. // <c r="A15" s="2" />
  159. // <c r="B15" s="2" />
  160. // <c r="C15" s="2" />
  161. // <c r="D15" s="2" />
  162. // <c r="E15" s="2" />
  163. // <c r="F15" s="1" />
  164. // <c r="G15" s="1" />
  165. // </row>
  166. //
  167. // Noteice: this method could be very slow for large spreadsheets (more than 3000 rows one sheet).
  168. func checkRow(xlsx xlsxWorksheet) xlsxWorksheet {
  169. buffer := bytes.Buffer{}
  170. for k, v := range xlsx.SheetData.Row {
  171. lenCol := len(v.C)
  172. if lenCol < 1 {
  173. continue
  174. }
  175. endR := getColIndex(v.C[lenCol-1].R)
  176. endRow := getRowIndex(v.C[lenCol-1].R)
  177. endCol := titleToNumber(endR)
  178. if lenCol < endCol {
  179. oldRow := xlsx.SheetData.Row[k].C
  180. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  181. tmp := []xlsxC{}
  182. for i := 0; i <= endCol; i++ {
  183. buffer.WriteString(toAlphaString(i + 1))
  184. buffer.WriteString(strconv.Itoa(endRow))
  185. tmp = append(tmp, xlsxC{
  186. R: buffer.String(),
  187. })
  188. buffer.Reset()
  189. }
  190. xlsx.SheetData.Row[k].C = tmp
  191. for _, y := range oldRow {
  192. colAxis := titleToNumber(getColIndex(y.R))
  193. xlsx.SheetData.Row[k].C[colAxis] = y
  194. }
  195. }
  196. }
  197. return xlsx
  198. }
  199. // UpdateLinkedValue fix linked values within a spreadsheet are not updating.
  200. // This function will be remove value tag when met a cell have a linked value.
  201. // Reference https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  202. //
  203. // Notice: after open XLSX file Excel will be update linked value and generate
  204. // new value and will prompt save file or not.
  205. //
  206. // For example:
  207. //
  208. // <row r="19" spans="2:2">
  209. // <c r="B19">
  210. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  211. // <v>100</v>
  212. // </c>
  213. // </row>
  214. //
  215. // to
  216. //
  217. // <row r="19" spans="2:2">
  218. // <c r="B19">
  219. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  220. // </c>
  221. // </row>
  222. func (f *File) UpdateLinkedValue() {
  223. for i := 1; i <= f.SheetCount; i++ {
  224. var xlsx xlsxWorksheet
  225. name := `xl/worksheets/sheet` + strconv.Itoa(i) + `.xml`
  226. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  227. for indexR, row := range xlsx.SheetData.Row {
  228. for indexC, col := range row.C {
  229. if col.F != nil && col.V != `` {
  230. xlsx.SheetData.Row[indexR].C[indexC].V = ``
  231. xlsx.SheetData.Row[indexR].C[indexC].T = ``
  232. }
  233. }
  234. }
  235. output, _ := xml.Marshal(xlsx)
  236. f.saveFileList(name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  237. }
  238. }