1. 需求
前端上传Excel文件,并根据Excel文件的模板内容解析字段到页面上,这个过程不需要后端参与。
主要用到了 XLSX.utils.sheet_to_json
2. 实现
2.1 HTML
<el-upload
style="margin-left: 20px"
:auto-upload="false"
class="upload-demo"
drag
accept=".xls,.xlsx"
:on-change="handleChangeFile"
:limit="1"
action="#">
<!-- <i class="el-icon-upload"></i>-->
<div class="el-upload__text">点击或将文件拖拽到这里上传</div>
</el-upload>
2.2 js逻辑
方法1(推荐):
import XLSX from 'xlsx';
handleChangeFile(file) {
const reader = new FileReader();
reader.onload = () => {
const txt = reader.result;
const wb = XLSX.read(txt, {
type: 'binary',
});
const json = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
// 到json就可以获取到解析后的结果了
this.xxx = xxx; // 把结果更新到页面上
}
reader.readAsBinaryString(file.raw);
},
方法2:
// 导入表格
handleChangeFile1(param) {
const that = this;
that.file2Xce(param).then((item) => {
if (item && item.length > 0) {
// xlsxJson就是解析出来的json数据,数据格式如下
// [{sheetName: sheet1, sheet: sheetData }]
if (item[0] && item[0].sheet && item[0].sheet.length) {
// that.tableData = item[0].sheet; // 把数据塞到表格预览
console.log('有的----', item[0].sheet);
}
}
}).catch((error) => {
// loading.close();
console.log('importExcel error', error);
});
},
/**
* 解析文件
* @param {Object} file
*/
file2Xce(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsBinaryString(file.raw);
reader.onload = (e) => {
const data = e.target.result;
this.wb = XLSX.read(data, {
type: 'binary',
});
const result = [];
this.wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName,
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
});
});
resolve(result);
};
});
},