springboot数据库导出excel
时间: 2023-04-26 13:06:42 浏览: 263
Spring Boot可以使用Apache POI库将数据库数据导出为Excel文件。以下是实现步骤:
1. 添加Apache POI库的依赖
在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>
```
2. 创建Excel文件
使用Apache POI库创建Excel文件,可以使用以下代码:
```
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Age");
List<User> userList = userService.getAllUsers();
int rowNum = 1;
for (User user : userList) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
FileOutputStream fileOut = new FileOutputStream("userList.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
```
3. 导出Excel文件
使用Spring Boot的RestController注解创建一个RESTful API,将Excel文件作为响应返回给客户端,可以使用以下代码:
```
@GetMapping("/export")
public void exportToExcel(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=userList.xlsx");
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Age");
List<User> userList = userService.getAllUsers();
int rowNum = 1;
for (User user : userList) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
```
在浏览器中访问http://localhost:8080/export,将会下载名为userList.xlsx的Excel文件。
阅读全文