springboot项目将apply表中的数据导出excel表
时间: 2023-12-18 10:03:20 浏览: 101
要将apply表中的数据导出到Excel表中,可以使用Apache POI库。步骤如下:
1. 添加Apache POI依赖
在pom.xml文件中添加以下依赖:
```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文件
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Apply Data");
```
3. 创建表头
```java
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Email");
```
4. 添加数据
```java
List<Apply> applies = applyService.getAllApplies();
int rowNum = 1;
for (Apply apply : applies) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(apply.getId());
row.createCell(1).setCellValue(apply.getName());
row.createCell(2).setCellValue(apply.getEmail());
}
```
5. 输出Excel文件
```java
response.setHeader("Content-disposition", "attachment;filename=apply_data.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
```
完整的Controller代码如下:
```java
@RestController
@RequestMapping("/apply")
public class ApplyController {
@Autowired
private ApplyService applyService;
@GetMapping("/export")
public void exportApplyData(HttpServletResponse response) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Apply Data");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Email");
List<Apply> applies = applyService.getAllApplies();
int rowNum = 1;
for (Apply apply : applies) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(apply.getId());
row.createCell(1).setCellValue(apply.getName());
row.createCell(2).setCellValue(apply.getEmail());
}
response.setHeader("Content-disposition", "attachment;filename=apply_data.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
}
```
这样就可以将apply表中的数据导出到Excel表中了。
阅读全文
相关推荐


















