背景:
需要导入excel,并获取Excel文件中的内容
最后需要的数据格式:
[
{
name:'tom',
age:18,
gender:'男'
},
{
name:'candy',
age:18,
gender:'女'
}
]
代码如下:
// template
// 需要使用input type="file"标签,如果想要改变样式,可以设置为透明,再定位到自定义样式的按钮上
<input
title=""
type="file"
id="importBtn"
@click="handleClick"
@change="handleImport"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
application/vnd.ms-excel"
/>
// script
//需要安装XLSX插件 => npm i xlsx -S
import XLSX from "xlsx";
data(){
return {
importData:[]
}
},
methods:{
// 如果点击上传后按了取消按钮,没有导入文件有可能导致报错,所以需要每次点击清空文件,强制触发change事件
handleClick() {
let dom = document.getElementById("importBtn");
if (dom) {
dom.value = "";
}
},
handleImport(event) {
let fileReader = new FileReader();
var file = event.currentTarget.files[0];
if (!file) {
return;
}
// 成功回调函数
fileReader.onload = async (ev) => {
try {
let datas = ev.target.result;
let workbook = XLSX.read(datas, {
type: "binary",
});
// excelData为excel读取出的数据,可以用来制定校验条件,如数据长度等
let excelData = XLSX.utils.sheet_to_json(
workbook.Sheets[workbook.SheetNames[0]]
);
// 将上面数据转换成需要的数据
let arr = [];
//item[]中的内容为Excel中数据的表头,上传的数据表头必须根据标题填写,否则无法读取
excelData.forEach((item) => {
let obj = {};
obj.name= item["名字"];
obj.age= item["年龄"];
obj.gender= item["性别"];
arr.push(obj);
});
this.importData = [...arr];
// this.importData则为最终获取到的数据
console.log(this.importData);
} catch (e) {
window.alert("文件类型不正确!");
return false;
}
};
// 读取文件 成功后执行上面的回调函数
fileReader.readAsBinaryString(file);
},
}