首先需要用到xlsx插件,直接安装即可
npm install xlsx
下面的代码为封装函数,使用el-upload将导入的Excel文件转成json格式的数据
import XLSX from "xlsx";
function file2Xce(file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader();
reader.onload = function (e) {
const data = e.target.result;
this.wb = XLSX.read(data, {
type: "binary"
});
const result = [];
this.wb.SheetNames.forEach(sheetName => {
result.push({
sheetName: sheetName,
sheet: XLSX.utlis.sheet_to_json(this.wb.Sheet[sheetName])
});
});
resolve(result);
}
reader.readAsBinaryString(file.raw)
});
}
最后是el-upload的方法使用
<template>
<el-upload
:auto-upload="false"
style="display: inline"
:show-file-list="false"
action="#"
:on-change="handleOnchange"
accept=".xlsx, .xls"
>
<el-button type="primary">导入Excel</el-button>
</el-upload>
</template>
method: {
handleOnchange(val) {
file2Xce(val).then(item => {
console.log(item)
})
}
}