1、安装插件
npm install js-xlsx file-saver -S
npm install script-loader -S -D //它帮我们挂载了,不需要引入到main.js里面
2、在src下创建一个文件夹vendor,并且引入Export2Excel.js
此处附上我项目中vendor的链接,直接拷过去就好:
vendor文件拷贝链接
3、html中表格
<el-table
id="excel-table"
v-loading="loading"
ref="filterTable"
:data="tableData" //表格中显示的是tableDate中的内容
style="width: 100%">
<el-table-column
prop="id"
label="Id"
sortable
width="80"
></el-table-column>
<el-table-column
prop="date"
label="日期"
sortable
width="180"
column-key="date"
:formatter="fmtTime"
>
</el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址" :formatter="formatter"></el-table-column>
<el-table-column
prop="tag"
label="标签"
width="100"
:filters="[{ text: '家', value: '家' }, { text: '公司', value: '公司' }]"
:filter-method="filterTag"
filter-placement="bottom-end"
>
<template slot-scope="scope">
<el-tag
:type="scope.row.tag === '家' ? 'primary' : 'success'"
disable-transitions
>{{scope.row.tag}}</el-tag>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button @click="dialogFormVisible = true" size="mini" type="primary">Edit</el-button>
<el-button @click="del(scope.row.id)" size="mini" type="danger">Delete</el-button>
</template>
</el-table-column>
</el-table>
4、button下载按钮
<el-button
:loading="downloadLoading"
class="filter-item"
type="primary"
icon="el-icon-download"
@click="handleDownload" //绑定了handleDownload方法
>Export</el-button>
5、tableDate中的数据,这个可根据自己的要求来
tableData: [
{
id: 1,
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
tag: "家"
},
{
id: 2,
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
tag: "公司"
},
{
id: 3,
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
tag: "家"
},
{
id: 4,
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
tag: "公司"
},
{
id: 5,
date: "2016-04-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
tag: "公司"
}
],
6、下载按钮绑定的方法handleDownload
handleDownload() {
// this.downloadLoading = true;
import("@/vendor/Export2Excel").then(excel => {
const tHeader = ["id", "date", "name", "address", "tag"];//要导出后表头是什么,可以跟tableDate中的表头不一致
const filterVal = [
"id",
"date",
"name",
"address",
"tag"
];
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];
}
})
);
},