excelize.go 11 KB

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