excelize.go 13 KB

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