需求:
用 vue 和 easyexcel 将查询出的表格数据导出成 excel 文档;
问题:
1、点击导出按钮,没有反应,后台也没有错误;
2、导出excel 成功后,有个别数据列没有数据。
问题1原因:
二进制文件流乱码,现象如下图所示,导致文件流不能变为弹窗下载
问题2原因:
easyexcel 读写反射对象用到了Cglib,所以成员变量必须符合驼峰规范,而且使用@Data不能使用@Accessors(chain = true)。
解决办法:
问题1解决办法:
办法1(不需要 token )
<template>
<div>
<el-button @click="downloadFile" type="primary">导出 Excel</el-button>
<iframe id="ifile" style="display:none"></iframe>
</div>
</template>
<script>
methods:{
// 导出 Excel
downloadFile() {
var dom=document.getElementById('ifile');
dom.src= this.downloadFileUrl +`/pay/exportExcel?
userId=${this.form.userId}&orderNumber=${this.form.orderNumber}&stime=${this.form.stime}&etime=${this.form.etime}&status=${this.form.status}&payChannel=${this.form.payChannel}`;
}
},
</script>
办法2(需要使用 token )--- 这种方法亲测好用
使用javascript的内置对象来解析,方法就是使用axios请求 请求过来的二进制文件流进行解析。
// 导出 Excel
downloadFile() { // 这是methods中的方法
downLoadPayListFn({this.form}).then(res => {
// 就是通过axios请求进行拦截 添加token form 是筛选条件
const fileName = '测试表格123.xls';
if ('download' in document.createElement('a')) { // 非IE下载
const blob = new Blob([res], {type: 'application/ms-excel'});
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
})
},
blob是js的内置对象 就是将其转化为文件。
// 上面代码段封装导出数据方法
export function downLoadPayListFn(obj) {
return fetch({
url: '/admin/pay/exportExcel',
method: 'get',
params: obj,
responseType: 'blob',
/* header: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
} */
});
}
在这里一定要加上 responseType: 'blob',否则不会生效 切记!!!!
看网上写的是这个样子 当然也根据后台返回给你的数据进行展示 我们后台返回的数据没有进行包装 所以直接就是response,搞就完事了.
问题2解决办法:
把实体类的字段的首字母修改为小写,使之符合驼峰规范,即可。
参考内容:
链接:https://www.jianshu.com/p/520d296fd2a3
来源:简书
链接:https://blog.csdn.net/kangrushuai/article/details/117749118
来源:CSDN