excelize.go 11 KB

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