excelize.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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, 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, 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. 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. completeRow(&xlsx, rows, cell)
  108. 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, axis, 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. 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. completeRow(&xlsx, rows, cell)
  146. 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, axis, 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. 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. completeRow(&xlsx, rows, cell)
  181. 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) {
  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. }
  211. // Completion row element tags of XML in a sheet.
  212. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  213. currentRows := len(xlsx.SheetData.Row)
  214. if currentRows > 1 {
  215. lastRow := xlsx.SheetData.Row[currentRows-1].R
  216. if lastRow >= row {
  217. row = lastRow
  218. }
  219. }
  220. sheetData := xlsxSheetData{}
  221. existsRows := map[int]int{}
  222. for k, v := range xlsx.SheetData.Row {
  223. existsRows[v.R] = k
  224. }
  225. for i := 0; i < row; i++ {
  226. _, ok := existsRows[i+1]
  227. if ok {
  228. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  229. continue
  230. }
  231. sheetData.Row = append(sheetData.Row, xlsxRow{
  232. R: i + 1,
  233. })
  234. }
  235. buffer := bytes.Buffer{}
  236. for ii := 0; ii < row; ii++ {
  237. start := len(sheetData.Row[ii].C)
  238. if start == 0 {
  239. for iii := start; iii < cell; iii++ {
  240. buffer.WriteString(toAlphaString(iii + 1))
  241. buffer.WriteString(strconv.Itoa(ii + 1))
  242. sheetData.Row[ii].C = append(sheetData.Row[ii].C, xlsxC{
  243. R: buffer.String(),
  244. })
  245. buffer.Reset()
  246. }
  247. }
  248. }
  249. xlsx.SheetData = sheetData
  250. }
  251. // Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible
  252. // Office Excel 2007.
  253. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  254. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  255. 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">`
  256. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  257. return workbookMarshal
  258. }
  259. // Check XML tags and fix discontinuous case. For example:
  260. //
  261. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  262. // <c r="A15" s="2" />
  263. // <c r="B15" s="2" />
  264. // <c r="F15" s="1" />
  265. // <c r="G15" s="1" />
  266. // </row>
  267. //
  268. // in this case, we should to change it to
  269. //
  270. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  271. // <c r="A15" s="2" />
  272. // <c r="B15" s="2" />
  273. // <c r="C15" s="2" />
  274. // <c r="D15" s="2" />
  275. // <c r="E15" s="2" />
  276. // <c r="F15" s="1" />
  277. // <c r="G15" s="1" />
  278. // </row>
  279. //
  280. // Noteice: this method could be very slow for large spreadsheets (more than
  281. // 3000 rows one sheet).
  282. func checkRow(xlsx *xlsxWorksheet) {
  283. buffer := bytes.Buffer{}
  284. for k, v := range xlsx.SheetData.Row {
  285. lenCol := len(v.C)
  286. if lenCol < 1 {
  287. continue
  288. }
  289. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  290. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  291. endCol := titleToNumber(endR) + 1
  292. if lenCol < endCol {
  293. oldRow := xlsx.SheetData.Row[k].C
  294. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  295. tmp := []xlsxC{}
  296. for i := 0; i <= endCol; i++ {
  297. buffer.WriteString(toAlphaString(i + 1))
  298. buffer.WriteString(strconv.Itoa(endRow))
  299. tmp = append(tmp, xlsxC{
  300. R: buffer.String(),
  301. })
  302. buffer.Reset()
  303. }
  304. xlsx.SheetData.Row[k].C = tmp
  305. for _, y := range oldRow {
  306. colAxis := titleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  307. xlsx.SheetData.Row[k].C[colAxis] = y
  308. }
  309. }
  310. }
  311. }
  312. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  313. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  314. // cell have a linked value. Reference
  315. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  316. //
  317. // Notice: after open XLSX file Excel will be update linked value and generate
  318. // new value and will prompt save file or not.
  319. //
  320. // For example:
  321. //
  322. // <row r="19" spans="2:2">
  323. // <c r="B19">
  324. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  325. // <v>100</v>
  326. // </c>
  327. // </row>
  328. //
  329. // to
  330. //
  331. // <row r="19" spans="2:2">
  332. // <c r="B19">
  333. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  334. // </c>
  335. // </row>
  336. //
  337. func (f *File) UpdateLinkedValue() {
  338. for i := 1; i <= f.SheetCount; i++ {
  339. var xlsx xlsxWorksheet
  340. name := "xl/worksheets/sheet" + strconv.Itoa(i) + ".xml"
  341. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  342. for indexR, row := range xlsx.SheetData.Row {
  343. for indexC, col := range row.C {
  344. if col.F != nil && col.V != "" {
  345. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  346. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  347. }
  348. }
  349. }
  350. output, _ := xml.Marshal(xlsx)
  351. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  352. }
  353. }