excelize.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 = 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. style, _ := f.NewStyle(`{"number_format": 22}`)
  129. f.SetCellStyle(sheet, axis, axis, style)
  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 = f.mergeCellsParser(xlsx, axis)
  157. col := string(strings.Map(letterOnlyMapF, axis))
  158. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  159. xAxis := row - 1
  160. yAxis := TitleToNumber(col)
  161. rows := xAxis + 1
  162. cell := yAxis + 1
  163. completeRow(xlsx, rows, cell)
  164. completeCol(xlsx, rows, cell)
  165. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  166. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  167. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  168. }
  169. // prepareCellStyle provides function to prepare style index of cell in
  170. // worksheet by given column index and style index.
  171. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  172. if xlsx.Cols != nil && style == 0 {
  173. for _, v := range xlsx.Cols.Col {
  174. if v.Min <= col && col <= v.Max {
  175. style = v.Style
  176. }
  177. }
  178. }
  179. return style
  180. }
  181. // SetCellStr provides function to set string type value of a cell. Total number
  182. // of characters that a cell can contain 32767 characters.
  183. func (f *File) SetCellStr(sheet, axis, value string) {
  184. xlsx := f.workSheetReader(sheet)
  185. axis = f.mergeCellsParser(xlsx, axis)
  186. if len(value) > 32767 {
  187. value = value[0:32767]
  188. }
  189. col := string(strings.Map(letterOnlyMapF, axis))
  190. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  191. xAxis := row - 1
  192. yAxis := TitleToNumber(col)
  193. rows := xAxis + 1
  194. cell := yAxis + 1
  195. completeRow(xlsx, rows, cell)
  196. completeCol(xlsx, rows, cell)
  197. // Leading space(s) character detection.
  198. if len(value) > 0 {
  199. if value[0] == 32 {
  200. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  201. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  202. Value: "preserve",
  203. }
  204. }
  205. }
  206. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  207. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  208. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  209. }
  210. // SetCellDefault provides function to set string type value of a cell as
  211. // default format without escaping the cell.
  212. func (f *File) SetCellDefault(sheet, axis, value string) {
  213. xlsx := f.workSheetReader(sheet)
  214. axis = f.mergeCellsParser(xlsx, axis)
  215. col := string(strings.Map(letterOnlyMapF, axis))
  216. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  217. xAxis := row - 1
  218. yAxis := TitleToNumber(col)
  219. rows := xAxis + 1
  220. cell := yAxis + 1
  221. completeRow(xlsx, rows, cell)
  222. completeCol(xlsx, rows, cell)
  223. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  224. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  225. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  226. }
  227. // Completion column element tags of XML in a sheet.
  228. func completeCol(xlsx *xlsxWorksheet, row, cell int) {
  229. if len(xlsx.SheetData.Row) < cell {
  230. for i := len(xlsx.SheetData.Row); i < cell; i++ {
  231. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  232. R: i + 1,
  233. })
  234. }
  235. }
  236. buffer := bytes.Buffer{}
  237. for k, v := range xlsx.SheetData.Row {
  238. if len(v.C) < cell {
  239. start := len(v.C)
  240. for iii := start; iii < cell; iii++ {
  241. buffer.WriteString(ToAlphaString(iii))
  242. buffer.WriteString(strconv.Itoa(k + 1))
  243. xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
  244. R: buffer.String(),
  245. })
  246. buffer.Reset()
  247. }
  248. }
  249. }
  250. }
  251. // completeRow provides function to check and fill each column element for a
  252. // single row and make that is continuous in a worksheet of XML by given row
  253. // index and axis.
  254. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  255. currentRows := len(xlsx.SheetData.Row)
  256. if currentRows > 1 {
  257. lastRow := xlsx.SheetData.Row[currentRows-1].R
  258. if lastRow >= row {
  259. row = lastRow
  260. }
  261. }
  262. for i := currentRows; i < row; i++ {
  263. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  264. R: i + 1,
  265. })
  266. }
  267. buffer := bytes.Buffer{}
  268. for ii := currentRows; ii < row; ii++ {
  269. start := len(xlsx.SheetData.Row[ii].C)
  270. if start == 0 {
  271. for iii := start; iii < cell; iii++ {
  272. buffer.WriteString(ToAlphaString(iii))
  273. buffer.WriteString(strconv.Itoa(ii + 1))
  274. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  275. R: buffer.String(),
  276. })
  277. buffer.Reset()
  278. }
  279. }
  280. }
  281. }
  282. // checkSheet provides function to fill each row element and make that is
  283. // continuous in a worksheet of XML.
  284. func checkSheet(xlsx *xlsxWorksheet) {
  285. row := len(xlsx.SheetData.Row)
  286. if row >= 1 {
  287. lastRow := xlsx.SheetData.Row[row-1].R
  288. if lastRow >= row {
  289. row = lastRow
  290. }
  291. }
  292. sheetData := xlsxSheetData{}
  293. existsRows := map[int]int{}
  294. for k, v := range xlsx.SheetData.Row {
  295. existsRows[v.R] = k
  296. }
  297. for i := 0; i < row; i++ {
  298. _, ok := existsRows[i+1]
  299. if ok {
  300. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  301. continue
  302. }
  303. sheetData.Row = append(sheetData.Row, xlsxRow{
  304. R: i + 1,
  305. })
  306. }
  307. xlsx.SheetData = sheetData
  308. }
  309. // replaceWorkSheetsRelationshipsNameSpace provides function to replace
  310. // xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
  311. // Office Excel 2007.
  312. func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
  313. oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  314. 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">`
  315. workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  316. return workbookMarshal
  317. }
  318. // checkRow provides function to check and fill each column element for all rows
  319. // and make that is continuous in a worksheet of XML. For example:
  320. //
  321. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  322. // <c r="A15" s="2" />
  323. // <c r="B15" s="2" />
  324. // <c r="F15" s="1" />
  325. // <c r="G15" s="1" />
  326. // </row>
  327. //
  328. // in this case, we should to change it to
  329. //
  330. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  331. // <c r="A15" s="2" />
  332. // <c r="B15" s="2" />
  333. // <c r="C15" s="2" />
  334. // <c r="D15" s="2" />
  335. // <c r="E15" s="2" />
  336. // <c r="F15" s="1" />
  337. // <c r="G15" s="1" />
  338. // </row>
  339. //
  340. // Noteice: this method could be very slow for large spreadsheets (more than
  341. // 3000 rows one sheet).
  342. func checkRow(xlsx *xlsxWorksheet) {
  343. buffer := bytes.Buffer{}
  344. for k, v := range xlsx.SheetData.Row {
  345. lenCol := len(v.C)
  346. if lenCol < 1 {
  347. continue
  348. }
  349. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  350. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  351. endCol := TitleToNumber(endR) + 1
  352. if lenCol < endCol {
  353. oldRow := xlsx.SheetData.Row[k].C
  354. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  355. tmp := []xlsxC{}
  356. for i := 0; i <= endCol; i++ {
  357. buffer.WriteString(ToAlphaString(i))
  358. buffer.WriteString(strconv.Itoa(endRow))
  359. tmp = append(tmp, xlsxC{
  360. R: buffer.String(),
  361. })
  362. buffer.Reset()
  363. }
  364. xlsx.SheetData.Row[k].C = tmp
  365. for _, y := range oldRow {
  366. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  367. xlsx.SheetData.Row[k].C[colAxis] = y
  368. }
  369. }
  370. }
  371. }
  372. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  373. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  374. // cell have a linked value. Reference
  375. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  376. //
  377. // Notice: after open XLSX file Excel will be update linked value and generate
  378. // new value and will prompt save file or not.
  379. //
  380. // For example:
  381. //
  382. // <row r="19" spans="2:2">
  383. // <c r="B19">
  384. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  385. // <v>100</v>
  386. // </c>
  387. // </row>
  388. //
  389. // to
  390. //
  391. // <row r="19" spans="2:2">
  392. // <c r="B19">
  393. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  394. // </c>
  395. // </row>
  396. //
  397. func (f *File) UpdateLinkedValue() {
  398. for i := 1; i <= f.SheetCount; i++ {
  399. xlsx := f.workSheetReader("sheet" + strconv.Itoa(i))
  400. for indexR, row := range xlsx.SheetData.Row {
  401. for indexC, col := range row.C {
  402. if col.F != nil && col.V != "" {
  403. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  404. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  405. }
  406. }
  407. }
  408. }
  409. }