vue+axios 与spring boot EasyExcel实现后台导出excel并下载
前端代码export function download() {return request({url: 'api/download',method: 'get',responseType: 'blob'})}exportExcel() {download().then(res => {debugger...
·
前端代码
export function download() {
return request({
url: 'api/download',
method: 'get',
responseType: 'blob'
})
}
exportExcel() {
download()
.then(res => {
debugger
let blob = new Blob([res], { type: 'application/xlsx' })
let url = window.URL.createObjectURL(blob)
const link = document.createElement('a') // 创建a标签
link.href = url
link.download = 'download.xlsx' // 重命名文件
link.click()
URL.revokeObjectURL(url)
})
}
后台controller代码
@Log("导出excel")
@ApiOperation(value = "查询LawCaseCollectMain")
@GetMapping(value = "/lawCaseCollectMain/download")
public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
// 这里需要设置不关闭流
EasyExcel.write(response.getOutputStream(), LawCaseCollectMainDownloadData.class)
.autoCloseStream(Boolean.FALSE)
.sheet("模板")
.doWrite(data());
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
JsonResponse.fail().setMsg("导出失败");
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)