excelize.go 11 KB

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