springboot和ajax下载excel文件
157浏览 · 2023-09-11 19:05:06
### 回答1:
要实现Spring Boot和Ajax下载[excel文件](https://geek.csdn.net/educolumn/058a2f001dec80db1ef2d7bf8bc67c6b?spm=1055.2569.3001.10083),可以按照以下步骤进行:
1. 在Controller中创建一个方法,该方法将生成[excel文件](https://geek.csdn.net/educolumn/058a2f001dec80db1ef2d7bf8bc67c6b?spm=1055.2569.3001.10083)并返回文件的字节数组。例如:
```java
@GetMapping("/downloadExcel")
public ResponseEntity<byte[]> downloadExcel() throws IOException {
byte[] excelBytes = generateExcel(); // 生成[excel文件](https://geek.csdn.net/educolumn/058a2f001dec80db1ef2d7bf8bc67c6b?spm=1055.2569.3001.10083)并返回字节数组
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLIC[ati](https://geek.csdn.net/educolumn/150d7073277950db5f09620704e791cf?spm=1055.2569.3001.10083)ON_OCTET_STREAM);
headers.setContentDis[pos](https://geek.csdn.net/educolumn/0399089ce1ac05d7729a569fd611cf73?spm=1055.2569.3001.10083)itionFormData("attachment", "data.xlsx"); // 设置文件名
headers.setContentLength(excelBytes.length);
return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);