excelize.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. Sheet map[string]*xlsxWorksheet
  18. SheetCount int
  19. }
  20. // OpenFile take the name of an XLSX file and returns a populated XLSX file
  21. // struct for it.
  22. func OpenFile(filename string) (*File, error) {
  23. file, err := os.Open(filename)
  24. if err != nil {
  25. return nil, err
  26. }
  27. defer file.Close()
  28. f, err := OpenReader(file)
  29. if err != nil {
  30. return nil, err
  31. }
  32. f.Path = filename
  33. return f, nil
  34. }
  35. // OpenReader take an io.Reader and return a populated XLSX file.
  36. func OpenReader(r io.Reader) (*File, error) {
  37. b, err := ioutil.ReadAll(r)
  38. if err != nil {
  39. return nil, err
  40. }
  41. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  42. if err != nil {
  43. return nil, err
  44. }
  45. file, sheetCount, err := ReadZipReader(zr)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return &File{
  50. Sheet: make(map[string]*xlsxWorksheet),
  51. checked: make(map[string]bool),
  52. XLSX: file,
  53. Path: "",
  54. SheetCount: sheetCount,
  55. }, nil
  56. }
  57. // SetCellValue provides function to set int or string type value of a cell.
  58. func (f *File) SetCellValue(sheet, axis string, value interface{}) {
  59. switch t := value.(type) {
  60. case int:
  61. f.SetCellInt(sheet, axis, value.(int))
  62. case int8:
  63. f.SetCellInt(sheet, axis, int(value.(int8)))
  64. case int16:
  65. f.SetCellInt(sheet, axis, int(value.(int16)))
  66. case int32:
  67. f.SetCellInt(sheet, axis, int(value.(int32)))
  68. case int64:
  69. f.SetCellInt(sheet, axis, int(value.(int64)))
  70. case float32:
  71. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
  72. case float64:
  73. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
  74. case string:
  75. f.SetCellStr(sheet, axis, t)
  76. case []byte:
  77. f.SetCellStr(sheet, axis, string(t))
  78. default:
  79. f.SetCellStr(sheet, axis, "")
  80. }
  81. }
  82. // workSheetReader provides function to get the pointer to the structure after
  83. // deserialization by given worksheet index.
  84. func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
  85. name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  86. worksheet := f.Sheet[name]
  87. if worksheet == nil {
  88. var xlsx xlsxWorksheet
  89. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  90. if f.checked == nil {
  91. f.checked = make(map[string]bool)
  92. }
  93. ok := f.checked[name]
  94. if !ok {
  95. checkRow(&xlsx)
  96. f.checked[name] = true
  97. }
  98. f.Sheet[name] = &xlsx
  99. worksheet = f.Sheet[name]
  100. }
  101. return worksheet
  102. }
  103. // SetCellInt provides function to set int type value of a cell.
  104. func (f *File) SetCellInt(sheet, axis string, value int) {
  105. xlsx := f.workSheetReader(sheet)
  106. axis = strings.ToUpper(axis)
  107. if xlsx.MergeCells != nil {
  108. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  109. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  110. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  111. }
  112. }
  113. }
  114. col := string(strings.Map(letterOnlyMapF, axis))
  115. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  116. xAxis := row - 1
  117. yAxis := titleToNumber(col)
  118. rows := xAxis + 1
  119. cell := yAxis + 1
  120. completeRow(xlsx, rows, cell)
  121. completeCol(xlsx, rows, cell)
  122. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  123. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  124. }
  125. // SetCellStr provides function to set string type value of a cell. Total number
  126. // of characters that a cell can contain 32767 characters.
  127. func (f *File) SetCellStr(sheet, axis, value string) {
  128. xlsx := f.workSheetReader(sheet)
  129. axis = strings.ToUpper(axis)
  130. if xlsx.MergeCells != nil {
  131. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  132. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  133. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  134. }
  135. }
  136. }
  137. if len(value) > 32767 {
  138. value = value[0:32767]
  139. }
  140. col := string(strings.Map(letterOnlyMapF, axis))
  141. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  142. xAxis := row - 1
  143. yAxis := titleToNumber(col)
  144. rows := xAxis + 1
  145. cell := yAxis + 1
  146. completeRow(xlsx, rows, cell)
  147. completeCol(xlsx, rows, cell)
  148. // Leading space(s) character detection.
  149. if len(value) > 0 {
  150. if value[0] == 32 {
  151. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  152. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  153. Value: "preserve",
  154. }
  155. }
  156. }
  157. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  158. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  159. }
  160. // SetCellDefault provides function to set string type value of a cell as
  161. // default format without escaping the cell.
  162. func (f *File) SetCellDefault(sheet, axis, value string) {
  163. xlsx := f.workSheetReader(sheet)
  164. axis = strings.ToUpper(axis)
  165. if xlsx.MergeCells != nil {
  166. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  167. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  168. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  169. }
  170. }
  171. }
  172. col := string(strings.Map(letterOnlyMapF, axis))
  173. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  174. xAxis := row - 1
  175. yAxis := titleToNumber(col)
  176. rows := xAxis + 1
  177. cell := yAxis + 1
  178. completeRow(xlsx, rows, cell)
  179. completeCol(xlsx, rows, cell)
  180. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  181. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  182. }
  183. // Completion column element tags of XML in a sheet.
  184. func completeCol(xlsx *xlsxWorksheet, row int, cell int) {
  185. if len(xlsx.SheetData.Row) < cell {
  186. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  187. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  188. R: i + 1,
  189. })
  190. }
  191. }
  192. buffer := bytes.Buffer{}
  193. for k, v := range xlsx.SheetData.Row {
  194. if len(v.C) < cell {
  195. start := len(v.C)
  196. for iii := start; iii < cell; iii++ {
  197. buffer.WriteString(toAlphaString(iii + 1))
  198. buffer.WriteString(strconv.Itoa(k + 1))
  199. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  200. R: buffer.String(),
  201. })
  202. buffer.Reset()
  203. }
  204. }
  205. }
  206. }
  207. // Completion row element tags of XML in a sheet.
  208. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  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. }
  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) {
  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. }
  308. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  309. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  310. // cell have a linked value. Reference
  311. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  312. //
  313. // Notice: after open XLSX file Excel will be update linked value and generate
  314. // new value and will prompt save file or not.
  315. //
  316. // For example:
  317. //
  318. // <row r="19" spans="2:2">
  319. // <c r="B19">
  320. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  321. // <v>100</v>
  322. // </c>
  323. // </row>
  324. //
  325. // to
  326. //
  327. // <row r="19" spans="2:2">
  328. // <c r="B19">
  329. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  330. // </c>
  331. // </row>
  332. //
  333. func (f *File) UpdateLinkedValue() {
  334. for i := 1; i <= f.SheetCount; i++ {
  335. xlsx := f.workSheetReader("sheet" + strconv.Itoa(i))
  336. for indexR, row := range xlsx.SheetData.Row {
  337. for indexC, col := range row.C {
  338. if col.F != nil && col.V != "" {
  339. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  340. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  341. }
  342. }
  343. }
  344. }
  345. }