后端
版本
springboot 2.4.4 + poi 4.0.0
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
@RequestMapping(value = "/customs")
public void CustomsExport(HttpServletResponse response,@RequestBody Bean bean) throws IOException {
...........(省略枯燥无味的poi代码)...........
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ServletOutputStream outputStream = response.getOutputStream();
this.setResponseHeader(response,fileName);
//将写好的workbook写到流中
workbook.write(byteArrayOutputStream);
//拷贝输出流内容到一个新的字节数组
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
//设置请求头
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
response.addDateHeader("Expires", 0);
} catch (Exception ex) {
ex.printStackTrace();
}
}
前端
表格里的数据在json里写死了
<!DOCTYPE html>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>下载</button>
<script>
const btns = document.querySelectorAll("button")
//模拟数据,原来的太长,直接删掉了
var data= {
}
btns[0].onclick = function () {
axios({
method: 'post',
url: 'url',
data: data,
responseType: "blob"
})
.then((res) => {
const link = document.createElement('a')
let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'})
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
//设置文件名
link.download = "test.xlsx"
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
}
</script>
</body>
</html>
效果
可以正常打开,不会报文件已损坏
之前一直是损坏文件,后端可以先把excel数据写死,通过地址栏访问接口测试,若没问题,大概率就是前段处理返回流有问题