excelize.go 12 KB

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