一、前端导出excel表格
1.安装vue-json-excel
1 | npm install vue-json-excel -S |
2.main.js里面引入并注册使用
1 2 | import JsonExcel from 'vue-json-excel' Vue.component('downloadExcel', JsonExcel) |
3、页面中使用
1 2 3 4 5 6 7 8 | <download-excel class = "export-excel-wrapper" :data = "json_data" :fields = "json_fields" name = "filename.xls"> <!-- 上面可以自定义自己的样式,还可以引用其他组件button --> <!-- <el-button type="primary" size="small">导出EXCEL</el-button> --> </download-excel> |
在这里说明一下组件的各个属性
1 2 3 4 5 6 7 | json_data:需要导出的数据 json_fields:自主选择要导出的字段,若不指定,默认导出全部数据中心全部字段 属性名 类型 描述 data Array 需要导出的数据,支持中文 fields Object 定义需要导出数据的字段 name String 导出excel的文件名 type String 导出excel的文件类型(xls,csv),默认是xls |
下面给个实例
注意以下几点
json_fields里面的属性是excel表每一列的title,注意多个词组组成的属性名要加双引号
如果需要自定义导出的数据,可以定义回调函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | data() { return { json_fields: { "Complete name": "name", //常规字段 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 " } ] ] }; } |
二、后端返回数据流, 前端导出下载xls文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | export function exportMethod() { axios({ method:'get', url: url+'params', responseType: 'blob' }).then((res) => { let blob = new Blob([res], {type: 'application/vnd.ms-excel'}) //兼容IE10 if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, '报表统计'); }else{ const link = document.createElement('a') link.style.display = 'none' link.href = URL.createObjectURL(blob) link.download = '报表统计' //下载的文件名 document.body.appendChild(link) link.click() document.body.removeChild(link) } }).catch(error => { console.log(error) }) } |