1、安装xlsx
npm install xlsx --save-dev
2、引入xlsx并封装读取excel方法
import * as XLSX from "xlsx";
/**
* 读取excel内容
* @param {*} file
* @returns
*/
export const readExcel = (file) => {
return new Promise((resolve, reject) => {
try {
//获取上传对象
const fileReader = new FileReader();
fileReader.onload = (event) => {
const fileData = event.target.result;
//读取excel文件
const workboot = XLSX.read(fileData, {
type: "binary",
});
//暂默认读取第一个Sheet
let sheel0 = workboot.SheetNames[0];
let blockArr = XLSX.utils.sheet_to_json(workboot.Sheets[sheel0]);
resolve(blockArr);
};
fileReader.readAsBinaryString(file);
} catch (e) {
reject(e);
}
});
};
3、页面引入方法,获取excel内容
<input class="uploadExcel" id="uploadExcel" type="file" @change="changeFile" accept=".xlsx">
const changeFile = async ()=>{
let xlsx = file.target.files[0];
if (!xlsx) return;
const data = await readExcel(file); //file指的是获取的excel文件对象,如e.file
console.log(data);
}