excelize.go 7.9 KB

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