springboot生成excel下载
时间: 2023-10-12 20:10:17 浏览: 42
Spring Boot 提供了很多库来生成 Excel 文件并下载。以下是一些生成 Excel 文件并下载的步骤:
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
这些依赖是 Apache POI 库,它提供了 Java 操作 Microsoft Office 格式的工具。
2. 创建 Excel 文件
创建一个 Excel 文件并填充数据。以下是一个简单的例子:
```
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// Create a header row
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("Name");
headerRow.createCell(1).setCellValue("Age");
// Create some data rows
Row dataRow1 = sheet.createRow(1);
dataRow1.createCell(0).setCellValue("John");
dataRow1.createCell(1).setCellValue(25);
Row dataRow2 = sheet.createRow(2);
dataRow2.createCell(0).setCellValue("Jane");
dataRow2.createCell(1).setCellValue(30);
```
这个例子创建了一个名为 "Sheet1" 的 Excel 表格,并填充了两行数据。
3. 将 Excel 文件转换为字节数组
将 Excel 文件转换为字节数组,以便在下载文件时使用。以下是一个简单的例子:
```
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] bytes = outputStream.toByteArray();
```
这个例子将 Excel 文件写入 ByteArrayOutputStream 中,并使用 toByteArray() 方法将其转换为字节数组。
4. 创建下载链接
创建一个下载链接,以便用户可以下载生成的 Excel 文件。以下是一个简单的例子:
```
@GetMapping("/download")
public ResponseEntity<byte[]> download() {
// Generate the Excel file
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// ...
// Convert the Excel file to a byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] bytes = outputStream.toByteArray();
// Create a HttpHeaders object to set the Content-Disposition header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "data.xlsx");
// Return the byte array as a ResponseEntity
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
```
这个例子创建了一个名为 "/download" 的 GET 请求处理程序,它生成 Excel 文件并将其转换为字节数组。然后,它创建了一个 HttpHeaders 对象,设置 Content-Disposition 头以指示浏览器下载文件。最后,它将字节数组包装在 ResponseEntity 中并返回。
现在,当用户访问 "/download" 链接时,会下载生成的 Excel 文件。