JS读写Excel文件

最近在做前端的excel导入导出需求,顺便整理下

Library

xlsx
open-file-dialog
file-saver
xlsx是xlsx格式文件的JS处理库,两个字:优秀。open-file-dialog是选择文件弹框,当然用原生都是可以的。
file-saver是文件输出的包。

读取Excel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
dialog({
multiple: false,
// 指定 .xlsx 格式
accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}, (json) => {
const file = json[0] // 单选一个文件
const reader = new FileReader()
// 读取完成后执行 onload
reader.onload = async (e) => {
const data = e.target.result
const workbook = XLSX.read(data, {
type: 'binary' // 设置二进制格式
})

// 遍历所有工作表
workbook.SheetNames.forEach(sheetName => {
// 将表内容转换成object数组
let XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName])
let json_object = XL_row_object
console.log(json_object)
})
}
// 异常处理
reader.onerror = (ex) => {
console.log(ex)
}
// 二进制格式读取文件
reader.readAsBinaryString(file)
})
})

具体看注释,主要原理就是二进制格式读取Excel文件,然后XLSX对数据进行解析,得到我们想要的object数组。

写入Excel

读取就更简单了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var wb = XLSX.utils.book_new()
const head = {'a':'第一列','b':'第二列'}
const result = [{
'a': '11',
'b': '12'
},{
'a': '21',
'b': '22'
}]

result.unshift(head)
// JSON转为Sheet
var ws = XLSX.utils.json_to_sheet(result[, {skipHeader: 1})
// Sheet加入到book中
XLSX.utils.book_append_sheet(wb, ws, `sheet1`)

var wbout = XLSX.write(wb, {bookType:'xlsx', type:'array'})
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), onlyHead ? `导入模板.xlsx` : `${moment().format('YYYY-MM-DD')}_nikki资料导出.xlsx`)
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout

看代码应该没难度,但是这个库有个问题,在issue看到它的header好像有BUG,而且单纯用header设置的话就做不了key映射(因为它header的设置只支持数组),所以我这里就用了一行数据作为我们的head,把head当做普通的数据来处理