方式1:引入js(Blob.js和 Export2Excel.js)
一、需要安装三个依赖:
npm install -S file-saver xlsx
npm install -D script-loader
二、项目中新建一个文件夹:(vendor—名字任取)
里面放置两个文件Blob.js和 Export2Excel.js。
百度可下载。
三、在.vue文件中
写这两个方法:其中list是表格的内容
export2Excel() {
require.ensure([], () => {
const { export_json_to_excel } = require(’…/…/vendor/Export2Excel’);
const tHeader = [‘序号’, ‘IMSI’, ‘MSISDN’, ‘证件号码’, ‘姓名’];
const filterVal = [‘ID’, ‘imsi’, ‘msisdn’, ‘address’, ‘name’];
const list = this.tableData;
const data = this.formatJson(filterVal, list);
export_json_to_excel(tHeader, data, ‘列表excel’);
})
},
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
}
方式2:使用vue-json-excel
1.安装插件
cnpm install vue-json-excel
2.min.js中引入使用
import JsonExcel from ‘vue-json-excel’
Vue.component(‘downloadExcel’, JsonExcel)
3.直接在页面中使用
//有数据,无需点击时获取 必需 data ,fields 属性
<download-excel :data="json_data" :fields="json_fields" name="filename.xls" >
<el-button type="warning">导出excel</el-button>
</download-excel>
<script>
export default {
data () {
return{
json_fields: {
'Complete name': 'name',
'City': 'city',
'Telephone': 'phone.mobile',
'Telephone 2' : {
field: 'phone.landline',
callback: (value) => {
return `Landline Phone - ${value}`;
}
},
},
json_data: [
{
'name': 'Tony Peña',
'city': 'New York',
'country': 'United States',
'birthdate': '1978-03-15',
'phone': {
'mobile': '1-541-754-3010',
'landline': '(541) 754-3010'
}
},
{
'name': 'Thessaloniki',
'city': 'Athens',
'country': 'Greece',
'birthdate': '1987-11-23',
'phone': {
'mobile': '+1 855 275 5071',
'landline': '(2741) 2621-244'
}
}
],
json_meta: [
[
{
'key': 'charset',
'value': 'utf-8'
}
]
],
}
}
}
</script>
//无数据,点击时获取 需要fetch ,fields属性 (有fetch时不需要data属性)
<download-excel :fetch= "fetchData" :fields="json_fields" :before-generate = "startDownload" :before-finish = "finishDownload" name="filename.xls" >
<el-button type="warning">导出excel</el-button>
</download-excel>
<script>
export default {
data () {
return{
json_fields: {
'Complete name': 'name',
'City': 'city',
'Telephone': 'phone.mobile',
'Telephone 2' : {
field: 'phone.landline',
callback: (value) => {
return `Landline Phone - ${value}`;
}
},
},
}
},
methods:{
async fetchData(){
const { list } = await this.$store.dispatch("get/infolist", {id : 1});
return list;
},
startDownload(){
alert('show loading');
},
finishDownload(){
alert('hide loading');
}
}
}
</script>