需求
前台勾选后把选择的用户作为参数传递到后台,后台执行逻辑后通过POI创建excel文件,响应给前台进行下载
前端操作// 前端请求
axios.post("/report/exportMemberExcel.do", this.multipleSelection,{responseType: 'blob'}).then((res) => {
if (!res) {
this.$message.error("下载模板文件失败");
return false;
}
console.log(res)
console.log(res.data)
const blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'});
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
let contentDisposition = res.headers['content-disposition']; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download = filename ; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})
// post参数:(url,data,config)
//后端的controller
// 批量导出会员信息
@RequestMapping("/exportMemberExcel")
public void exportMemberExcel(@RequestBody List<Member> list ,HttpServletRequest request, HttpServletResponse response){
//...
// 获取输出流
OutputStream out = response.getOutputStream();
//使用输出流进行表格下载,基于浏览器作为客户端下载
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
//指定以附件形式进行下载,文件名是固定的memberReport.xlsx
response.setHeader("Content-Disposition", "attachment;filename=memberReport.xlsx");
//写出文件
workbook.write(out);
out.flush();
out.close();
workbook.close();
//...
}
需要注意的东西
MIME类型 正常请求的输出 错误的情况错误的输出是乱码,同时打开ecxel提示错误,原因是没有在axios的请求中写config
{responseType: 'blob'}
网友评论