先安装xlsx依赖
npm install--save xlsx
我用的是view-ui-plus的上传组件和element plus是有区别的 下面会说
<Upload
class="upload-btn"
ref="upload"
:show-upload-list="false"
:format="['xlsx', 'xls']"
:max-size="2048"
:before-upload="handleBeforeUpload"
action="#"
>
<Button class="m-left-10">批量导入询价</Button>
</Upload>
在使用的页面引入
import XLSX from "xlsx";
新建tools.ts 创建readFile
/**
* 读取excel
* @param excel
* @param readExcel
* @returns
*/
export const readFile = (file: any) => {
return new Promise(resolve => {
let reader = new FileReader()
reader.readAsBinaryString(file)
reader.onload = (ev: any) => {
resolve(ev.target.result)
}
})
}
在使用的页面引入tools
import { readFile } from "@/utils/tools";
调用readFile
element plus组件 注意看注释
/**
* 文件上传
* element plus是on-change方法 同样是使用file参数
* 但是let dataBinary = await readFile(file) 要改成 readFile(file.row)
*/
private async handleBeforeUpload(file: any) {
let dataBinary = await readFile(file);
let workBook = XLSX.read(dataBinary, { type: "binary", cellDates: true });
let workSheet = workBook.Sheets[workBook.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(workSheet);
console.log(data, "data");
}
这时有些人会报错 TypeError: Cannot read properties of undefined (reading ‘read’)
卸载xlsx
npm uninstall xlsx
安装适配版本 我这里是0.16.0
npm install xlsx@0.16.0