excelize.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. checkSheet(&xlsx)
  96. checkRow(&xlsx)
  97. f.checked[name] = true
  98. }
  99. f.Sheet[name] = &xlsx
  100. worksheet = f.Sheet[name]
  101. }
  102. return worksheet
  103. }
  104. // SetCellInt provides function to set int type value of a cell.
  105. func (f *File) SetCellInt(sheet, axis string, value int) {
  106. xlsx := f.workSheetReader(sheet)
  107. axis = strings.ToUpper(axis)
  108. if xlsx.MergeCells != nil {
  109. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  110. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  111. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  112. }
  113. }
  114. }
  115. col := string(strings.Map(letterOnlyMapF, axis))
  116. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  117. xAxis := row - 1
  118. yAxis := titleToNumber(col)
  119. rows := xAxis + 1
  120. cell := yAxis + 1
  121. completeRow(xlsx, rows, cell)
  122. completeCol(xlsx, rows, cell)
  123. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  124. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  125. }
  126. // SetCellStr provides function to set string type value of a cell. Total number
  127. // of characters that a cell can contain 32767 characters.
  128. func (f *File) SetCellStr(sheet, axis, value string) {
  129. xlsx := f.workSheetReader(sheet)
  130. axis = strings.ToUpper(axis)
  131. if xlsx.MergeCells != nil {
  132. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  133. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  134. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  135. }
  136. }
  137. }
  138. if len(value) > 32767 {
  139. value = value[0:32767]
  140. }
  141. col := string(strings.Map(letterOnlyMapF, axis))
  142. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  143. xAxis := row - 1
  144. yAxis := titleToNumber(col)
  145. rows := xAxis + 1
  146. cell := yAxis + 1
  147. completeRow(xlsx, rows, cell)
  148. completeCol(xlsx, rows, cell)
  149. // Leading space(s) character detection.
  150. if len(value) > 0 {
  151. if value[0] == 32 {
  152. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  153. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  154. Value: "preserve",
  155. }
  156. }
  157. }
  158. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  159. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  160. }
  161. // SetCellDefault provides function to set string type value of a cell as
  162. // default format without escaping the cell.
  163. func (f *File) SetCellDefault(sheet, axis, value string) {
  164. xlsx := f.workSheetReader(sheet)
  165. axis = strings.ToUpper(axis)
  166. if xlsx.MergeCells != nil {
  167. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  168. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  169. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  170. }
  171. }
  172. }
  173. col := string(strings.Map(letterOnlyMapF, axis))
  174. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  175. xAxis := row - 1
  176. yAxis := titleToNumber(col)
  177. rows := xAxis + 1
  178. cell := yAxis + 1
  179. completeRow(xlsx, rows, cell)
  180. completeCol(xlsx, rows, cell)
  181. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  182. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  183. }
  184. // Completion column element tags of XML in a sheet.
  185. func completeCol(xlsx *xlsxWorksheet, row int, cell int) {
  186. if len(xlsx.SheetData.Row) < cell {
  187. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  188. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  189. R: i + 1,
  190. })
  191. }
  192. }
  193. buffer := bytes.Buffer{}
  194. for k, v := range xlsx.SheetData.Row {
  195. if len(v.C) < cell {
  196. start := len(v.C)
  197. for iii := start; iii < cell; iii++ {
  198. buffer.WriteString(toAlphaString(iii + 1))
  199. buffer.WriteString(strconv.Itoa(k + 1))
  200. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  201. R: buffer.String(),
  202. })
  203. buffer.Reset()
  204. }
  205. }
  206. }
  207. }
  208. // completeRow provides function to check and fill each column element for a
  209. // single row and make that is continuous in a worksheet of XML by given row
  210. // index and axis.
  211. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  212. currentRows := len(xlsx.SheetData.Row)
  213. if currentRows > 1 {
  214. lastRow := xlsx.SheetData.Row[currentRows-1].R
  215. if lastRow >= row {
  216. row = lastRow
  217. }
  218. }
  219. for i := currentRows; i < row; i++ {
  220. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  221. R: i + 1,
  222. })
  223. }
  224. buffer := bytes.Buffer{}
  225. for ii := currentRows; ii < row; ii++ {
  226. start := len(xlsx.SheetData.Row[ii].C)
  227. if start == 0 {
  228. for iii := start; iii < cell; iii++ {
  229. buffer.WriteString(toAlphaString(iii + 1))
  230. buffer.WriteString(strconv.Itoa(ii + 1))
  231. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  232. R: buffer.String(),
  233. })
  234. buffer.Reset()
  235. }
  236. }
  237. }
  238. }
  239. // checkSheet provides function to fill each row element and make that is
  240. // continuous in a worksheet of XML.
  241. func checkSheet(xlsx *xlsxWorksheet) {
  242. row := len(xlsx.SheetData.Row)
  243. if row > 1 {
  244. lastRow := xlsx.SheetData.Row[row-1].R
  245. if lastRow >= row {
  246. row = lastRow
  247. }
  248. }
  249. sheetData := xlsxSheetData{}
  250. existsRows := map[int]int{}
  251. for k, v := range xlsx.SheetData.Row {
  252. existsRows[v.R] = k
  253. }
  254. for i := 0; i < row; i++ {
  255. _, ok := existsRows[i+1]
  256. if ok {
  257. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  258. continue
  259. }
  260. sheetData.Row = append(sheetData.Row, xlsxRow{
  261. R: i + 1,
  262. })
  263. }
  264. xlsx.SheetData = sheetData
  265. }
  266. // replaceWorkSheetsRelationshipsNameSpace provides function to replace
  267. // xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
  268. // Office Excel 2007.
  269. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  270. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  271. 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">`
  272. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  273. return workbookMarshal
  274. }
  275. // checkRow provides function to check and fill each column element for all rows
  276. // and make that is continuous in a worksheet of XML. For example:
  277. //
  278. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  279. // <c r="A15" s="2" />
  280. // <c r="B15" s="2" />
  281. // <c r="F15" s="1" />
  282. // <c r="G15" s="1" />
  283. // </row>
  284. //
  285. // in this case, we should to change it to
  286. //
  287. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  288. // <c r="A15" s="2" />
  289. // <c r="B15" s="2" />
  290. // <c r="C15" s="2" />
  291. // <c r="D15" s="2" />
  292. // <c r="E15" s="2" />
  293. // <c r="F15" s="1" />
  294. // <c r="G15" s="1" />
  295. // </row>
  296. //
  297. // Noteice: this method could be very slow for large spreadsheets (more than
  298. // 3000 rows one sheet).
  299. func checkRow(xlsx *xlsxWorksheet) {
  300. buffer := bytes.Buffer{}
  301. for k, v := range xlsx.SheetData.Row {
  302. lenCol := len(v.C)
  303. if lenCol < 1 {
  304. continue
  305. }
  306. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  307. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  308. endCol := titleToNumber(endR) + 1
  309. if lenCol < endCol {
  310. oldRow := xlsx.SheetData.Row[k].C
  311. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  312. tmp := []xlsxC{}
  313. for i := 0; i <= endCol; i++ {
  314. buffer.WriteString(toAlphaString(i + 1))
  315. buffer.WriteString(strconv.Itoa(endRow))
  316. tmp = append(tmp, xlsxC{
  317. R: buffer.String(),
  318. })
  319. buffer.Reset()
  320. }
  321. xlsx.SheetData.Row[k].C = tmp
  322. for _, y := range oldRow {
  323. colAxis := titleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  324. xlsx.SheetData.Row[k].C[colAxis] = y
  325. }
  326. }
  327. }
  328. }
  329. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  330. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  331. // cell have a linked value. Reference
  332. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  333. //
  334. // Notice: after open XLSX file Excel will be update linked value and generate
  335. // new value and will prompt save file or not.
  336. //
  337. // For example:
  338. //
  339. // <row r="19" spans="2:2">
  340. // <c r="B19">
  341. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  342. // <v>100</v>
  343. // </c>
  344. // </row>
  345. //
  346. // to
  347. //
  348. // <row r="19" spans="2:2">
  349. // <c r="B19">
  350. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  351. // </c>
  352. // </row>
  353. //
  354. func (f *File) UpdateLinkedValue() {
  355. for i := 1; i <= f.SheetCount; i++ {
  356. xlsx := f.workSheetReader("sheet" + strconv.Itoa(i))
  357. for indexR, row := range xlsx.SheetData.Row {
  358. for indexC, col := range row.C {
  359. if col.F != nil && col.V != "" {
  360. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  361. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  362. }
  363. }
  364. }
  365. }
  366. }