excelize.go 11 KB

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