感谢评论区好兄弟提醒,我blod写错了,已经修改成blob
先查看后端代码
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.addHeader("responseType","blob");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + "订单详情"+ ".xls");
EasyExcel.write(response.getOutputStream(), Orders.class).autoCloseStream(Boolean.FALSE).sheet("订单详情").doWrite(pageInfo.getRecords());
确保数据是正常返回给前端浏览器


如果都没写错,
那么问题出在前端的axios:
1,axios要使用原生axios,写在js文件并且调用的方法不行
错误代码,如果是我写错了求指正
//导出excel
const getOrderPageExcel = (params) => {
return $axios({
url: '/order/daochu',
method: 'get',
params,
responseType: "blob",
cache: true
})
}
async daochu () {
getOrderPageExcel({ page: this.page, pageSize: this.pageSize, number: this.input || undefined, beginTime: this.beginTime || undefined, endTime: this.endTime || undefined }).then(res => {
console.log(res);
let link = document.createElement("a");
let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.setAttribute("download", decodeURI(Date.now()+'订单详情.xls'));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(err => {
this.$message.error('请求出错了:' + err)
})
},
完整代码
daochu () {
axios.get('/order/daochu',{
params:{ page: this.page, pageSize: this.pageSize, number: this.input || undefined, beginTime: this.beginTime || undefined, endTime: this.endTime || undefined },
responseType: "blob",
contentType: 'application/json'
}).then(res => {
console.log(res);
let link = document.createElement("a");
let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.setAttribute("download", decodeURI(Date.now()+'订单详情.xls'));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(err => {
this.$message.error('请求出错了:' + err)
})
},
博客内容涉及前端axios从后端获取Excel文件时遇到的问题。后端已设置正确响应头,但前端axios请求中,使用原生js的写法才能成功下载。错误代码示例显示了使用常规axios方法导致的问题,正确的实现包括设置responseType为'blob',创建并点击隐藏的a标签来触发下载。
7952





