(1)先安装js-export-excel插件
npm install js-export-excel --save
(2)引入js-export-excel
import ExportJsonExcel from 'js-export-excel';
(3)开始使用
<template>
<button @click="exportExcel">导出excel</button>
</template>
<script>
import ExportJsonExcel from 'js-export-excel';
export default {
name: 'exportExcel',
components: {
},
data() {
return {
tableData:[
{
name:'路人甲',
phone:'123456',
email:'123@123456.com'
},
{
name:'炮灰乙',
phone:'123456',
email:'123@123456.com'
},
{
name:'土匪丙',
phone:'123456',
email:'123@123456.com'
},
{
name:'流氓丁',
phone:'123456',
email:'123@123456.com'
}
],
propLabel:{
name:'姓名',
phone:'手机号',
email:'邮箱'
},
excelTable:[]
}
},
methods:{
exportExcel(){
const option = {};
this.tableData.forEach(item => {
let obj = {}
for(let k in item){
obj[this.propLabel[k]] = item[k];
}
this.excelTable.push(obj)
})
option.fileName = '学校学生统计数据'//文件名
let labelList = []
for(let k in this.propLabel){
labelList.push(this.propLabel[k])
}
option.datas = [
{
sheetData: this.excelTable ,//[{'姓名':'路人甲','phone':'123456','email':'123@123456.com'}]
sheetName: 'sheet1',
sheetFilter: labelList ,//表头数据对应的sheetData数据 ['姓名','手机号','邮箱']
sheetHeader: labelList ,//表头数据 ['姓名','手机号','邮箱']
columnWidths: ['4','8','8'], // 列宽 1代表20像素
},
{
sheetData: this.tableData,
sheetName: 'sheet2',
sheetFilter: Object.keys(this.propLabel) ,//表头数据对应的sheetData数据['name','phone','email']
sheetHeader: labelList ,//表头数据 ['姓名','手机号','邮箱']
columnWidths: ['8','8','8'], // 列宽 1代表20像素
}
]
const toExcel = new ExportJsonExcel(option)
toExcel.saveExcel()
}
}
}
</script>