excelize.go 11 KB

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