详细代码转 自https://blog.csdn.net/weixin_44846723/article/details/100886061
1.安装插件
npm install js-xlsx file-saver -S
npm install script-loader -S -D //它帮我们挂载了,不需要引入到main.js里面
2、在src下创建一个文件夹vendor,并且引入Export2Excel.js
此处附上我项目中vendor的链接,直接拷过去就好:
3.html
<template>
<div>
<el-button type="primary" @click="onexcel">导出数据</el-button>
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
</el-table>
</div>
</template>
<script>
export default{
data(){
return{
tableData: [{
id: 1,
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
id: 2,
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
id: 3,
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
id: 4,
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}],
}
},
methods:{
onexcel() {
// this.downloadLoading = true;
import("@/vendor/Export2Excel").then(excel => {
const tHeader = ["id", "date", "name", "address",];//要导出后表头是什么,可以跟tableDate中的表头不一致
const filterVal = [
"id",
"date",
"name",
"address"
];
const data = this.formatJson(filterVal, this. tableData)
// const data = this.tableData;
excel.export_json_to_excel({
header: tHeader,
data,
filename: "table-list" //导出文件的名,自定义就好
});
// this.downloadLoading = false;
});
},
//下载方法中,需要用到的格式化json的方法
formatJson(filterVal, jsonData) {
return jsonData.map(v =>
filterVal.map(j => {
if (j === "id") { //此处如没有要格式化的列,可以不用此判断
// return parseTime(v[j])
return v[j];
} else {
return v[j];
}
})
);
},
}
}
</script>