1、利用elementUI的上传组件el-upload
2、还要使用到 xlsx 插件
下载:npm install --save-dev xlsx
3、如果表格很复杂,一定要把这个文件做成多表格形式,否则无法正常读取内容。如:
例子
<el-upload
ref="upload"
action="https://jsonplaceholder.typicode.com/posts/"
class="upload-demo"
accept="xls,xlsx"
:show-file-list="false"
:auto-upload="false"
:multiple="false"
:on-change="fileOnChange">
<el-button slot="trigger" size="small" type="primary" icon="el-icon-plus">Excel导入</el-button>
</el-upload>
fileOnChange(file, fileList){
let files = {0:file.raw}
this.readExcel1(files);
},
readExcel1(files) {//表格导入
var that = this;
if(files.length<=0){//如果没有文件名
return false;
}else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
this.$Message.error('上传格式不正确,请上传xls或者xlsx格式');
return false;
}
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, {
type: 'binary'
});
const wsname1 = workbook.SheetNames[0];//取第一张表
const ws1 = XLSX.utils.sheet_to_json(workbook.Sheets[wsname1]);//生成第一张表的json表格内容
console.log('json表格内容',ws1)
try{
}catch(err){
console.log(err)
}
this.$refs.upload.value = '';
} catch (e) {
return false;
}
};
fileReader.readAsBinaryString(files[0]);
},
补充:读取出来的json对象的键很可能是中文,此时需要前端统一处理成与后端对应的英文
转换前
转换后
方法:
const newArr = ws1.map(item => {
return {
item1: item['属性名称'],
item2: item['属性类型'],
item3: item['属性标识'],
item4: item['唯一标识'],
item5: item['必填'],
item6: item['显示属性'],
item7: item['是否多值'],
item8: item['默认值']
}
})