excelize.go 13 KB

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