excelize.go 11 KB

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