在components/UploadExcel文件下 新建文件importExcel.vue
前端渲染
<template>
<div style="display:flex;">
<el-button class="filter-item" type="danger" @click="handleDownload" style="margin-left:10px;">下载表格</el-button>
<!-- 表格导入 v-waves-->
<el-upload style="margin-left:10px;" class="upload-demo" :limit="1"
action="" :multiple="false" :show-file-list="false"
accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
:http-request="httpRequest"
>
<el-button type="success">读取Excel文件</el-button>
</el-upload>
</div>
</template>
script 引入
import XLSX from 'xlsx'
data数据
export default {
data() {
return {
downloadLoading:false,
tableData: [],//导入表格数据
}
},
methods: {
//导入表格 预览
httpRequest(e) {
const file = e.file; // 文件信息
if (!file) {
return false
} else if (!/\.(xls|xlsx)$/.test(file.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 exlname = workbook.SheetNames[0];// 取第一张表
const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
//console.log(exl)
// 将 JSON 数据挂到 data 里
this.tableData = this.filterExcel(exl) //exl;
console.log(this.tableData)
} catch (e) {
console.log('出错了:', e)
return false
}
}
fileReader.readAsBinaryString(file);
},
//格式化
filterExcel(list) {
const arr = [];
list.map(v => {
const obj = {
add_name: v.配件名称,
sn_code: v.品牌编码,
oecode: v.OE编码,
nums: v.数量,
unit: v.单位,
price: v.采购价,
price_one: v.预售价1,
price_two: v.预售价2,
brands: v.品牌,
cars: v.车型,
msg: v.备注说明,
}
// obj.add_name = v.配件名称
arr.push(obj)
})
return arr;
},
//下载表格
handleDownload() {
this.downloadLoading = true
this.$confirm('是否下载表格模板?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info'
}).then(() => {
import('@/vendor/Export2Excel').then(excel => {
const tHeader = [
'配件名称',
'品牌编码',
'OE编码',
'数量',
'单位',
'采购价',
'预售价1',
'预售价2',
'品牌',
'车型',
'备注说明'
]
excel.export_json_to_excel({
header: tHeader,
data: []
})
this.downloadLoading = false
})
this.$message({
type: 'success',
message: '下载成功!'
});
}).catch(() => {
this.downloadLoading = false
this.$message({
type: 'info',
message: '取消下载'
});
});
},
}
}
在某也引入
表格内容
打印结果 console.log(exl)
这里的key键是中文,格式化很丑,大神是否有更好的方式
//格式化
filterExcel(list) {
const arr = [];
list.map(v => {
const obj = {
add_name: v.配件名称,
sn_code: v.品牌编码,
oecode: v.OE编码,
nums: v.数量,
unit: v.单位,
price: v.采购价,
price_one: v.预售价1,
price_two: v.预售价2,
brands: v.品牌,
cars: v.车型,
msg: v.备注说明,
}
// obj.add_name = v.配件名称
arr.push(obj)
})
return arr;
},
再优化 也最简单 好看点是
const obj = {
add_name: v["配件名称"],
sn_code: v["品牌编码"],
oecode: v["OE编码"],
nums: v["数量"],
unit: v["单位"],
price: v["采购价"],
price_one: v["预售价1"],
price_two: v["预售价2"],
brands: v["品牌"],
cars: v["车型"],
msg: v["备注说明"],
}
打印格式化的 console.log(this.tableData)