前言
突然来了需求,要求前端解析出上传文件中的数据,回显到页面上。以前一直是借助后端的帮忙,查了下资料发现前端有插件可以实现,备忘下~
1、可解析文件
2、支持框架
3、安装包
npm install xlsx
4、相关代码
1)HTML部分
<div >
{{ upload_file || "导入" }}
<input type="file" accept=".xls,.xlsx" class="upload_file" @change="readExcel($event)"/>
</div>
2)data 部分
import XLSX from "xlsx";//需要引入包
data () {
return {
upload_file:'',
data:[],
}
},
3)方法实现部分
readExcel(e) {
// 读取表格文件
let that = this;
const files = e.target.files;
if (files.length <= 0) {
return false;
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
this.$message({
message: "上传格式不正确,请上传xls或者xlsx格式",
type: "warning"
});
return false;
} else {
// 更新获取文件名
that.upload_file = files[0].name;
}
const fileReader = new FileReader();
fileReader.onload = ev => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, {
type: "binary"
});
const wsname = workbook.SheetNames[0]; //取第一张表
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
that.lists = [];
console.log('ws',ws);
// 从解析出来的数据中提取相应的数据
ws.forEach(item => {
that.data.push({
value_id: 0,
value_show_name: item.show_name,
value_name: item.name,
value_color: item.color,
is_deleted: '0'
});
});
that.visibleUp=false;
// 给后端发请求
// this.submit_form();
} catch (e) {
return false;
}
};
fileReader.readAsBinaryString(files[0]);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。