excelize.go 11 KB

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