首先引入依赖模块:
npm install xlsx --save
在需要解析excel的页面(vue文件)中引入依赖:
import XLSX from 'xlsx'
页面部分:
使用elementUI组件完成文件上传:
<!-- excel表格上传 -->
<el-upload
class="upload-demo"
drag
action="https://jsonplaceholder.typicode.com/posts/"
multiple
accept=".xlsx"
:on-exceed="exceed"
:limit="1"
:on-remove="remove"
:http-request="uploadFile"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">1次只能上传1个xls文件,且不超过500kb</div>
</el-upload>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 表格显示:
<!-- 上传的excel表格预览 -->
<div class="preview-excel">
<el-table class="listTable_ele" :data="listTable" stripe height="250" style="width:100%">
<el-table-column prop="name" label="姓名" width="200" align="center"></el-table-column>
<el-table-column prop="age" label="年龄" width="200" align="center"></el-table-column>
</el-table>
</div>
JS部分: 首先data中声明: listTable: [] 用于记录解析表格生成的表格数据 重要代码就是uploadFile方法来解析excel:
//解析excel
async uploadFile(params) {
const _file = params.file;
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, {
type: 'binary'
});
for (let sheet in workbook.Sheets) {
//循环读取每个文件
const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
//若当前sheet没有数据,则continue
if(sheetArray.length == 0){
continue;
}
console.log("读取文件");
console.log(sheetArray);
for(let item in sheetArray){
let rowTable = {};
//这里的rowTable的属性名注意要与上面表格的prop一致
//sheetArray的属性名与上传的表格的列名一致
rowTable.name = sheetArray[item].姓名;
rowTable.age = sheetArray[item].年龄;
this.listTable.push(rowTable)
}
}
} catch (e) {
this.$message.warning('文件类型不正确!');
}
};
fileReader.readAsBinaryString(_file);
},
//上传1个以上文件时弹窗提示错误
exceed: function() {
this.$message.error("最多只能上传1个xls文件");
},
//删除文件
remove() {
this.listTable = [];
}