因为项目采用element-ui
,为了简单直接使用它的 Upload
组件来搭建读取本地文档功能,因为是利用js-xlsx
在前端读取,所以要把 auto-upload
关掉
template
<el-upload
ref="upload"
action="/wm/upload/"
:show-file-list="false"
:on-change="readExcel"
:auto-upload="false">
<el-button
slot="trigger"
icon="el-icon-upload"
size="small"
type="primary">
上传文件
</el-button>
</el-upload>
methods
readExcel(file) {
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, {
type: 'binary',
});
for (let sheet in workbook.Sheets) {
const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
}
} catch (e) {
this.$message.warning('文件类型不正确!');
return false;
}
};
fileReader.readAsBinaryString(file.raw);
},