springboot导出Excel多个sheet
时间: 2023-07-03 08:29:29 浏览: 99
要在Spring Boot中导出多个sheet的Excel文件,可以使用Apache POI库。下面是一个简单的示例:
```java
@PostMapping("/export")
public ResponseEntity<byte[]> exportData() throws IOException {
// 创建一个工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建第一个sheet
XSSFSheet sheet1 = workbook.createSheet("Sheet1");
// 向第一个sheet中添加数据
// ...
// 创建第二个sheet
XSSFSheet sheet2 = workbook.createSheet("Sheet2");
// 向第二个sheet中添加数据
// ...
// 将工作簿转换为字节数组
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] bytes = outputStream.toByteArray();
// 设置响应头,告诉浏览器这是一个Excel文件
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "data.xlsx");
// 返回字节数组和响应头
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
```
在这个示例中,我们创建了一个`XSSFWorkbook`工作簿,并向其中添加了两个sheet。最后,我们将工作簿转换为字节数组,并设置响应头以将其作为Excel文件下载。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)