Front-end vue import to read excel content
1. Install the xlsx package
npm i xlsx
2. Introduce xlsx in the main.js file
import XLSX from xlsx
3. In the component, realize the function
1. Bind a function to the on-change event of the el-upload component of the uploaded file . Here my function is called handle 2. In the handle function, the file is read, and the read data is read through the filechange function , returned to the parent component
readFile(file) {
//文件读取
return new Promise((resolve) => {
let reader = new FileReader();
reader.readAsBinaryString(file); //以二进制的方式读取
reader.onload = (ev) => {
resolve(ev.target.result);
};
});
},
async handle(ev) {
let file = ev.raw;
if (this.lastUid == file.uid) {
return;
}
this.lastUid = file.uid;
if (file) {
if (
file.name.indexOf(".xls") != -1 ||
file.name.indexOf(".xlsx") != -1
) {
//这里进行了判断,只能读取这两种类型的文件。
let data = await this.readFile(file);
let workbook = XLSX.read(data, {
type: "binary", cellDates: true }); //解析二进制格式数据
let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet
let result = XLSX.utils.sheet_to_json(worksheet); //json数据格式
this.$emit("filechange", result);//将数据通过filechange函数,传递给父组件
}
}
},
3. Realize the effect
The imported form is
The obtained data format is: