springboot POI报表案例
时间: 2023-09-14 19:14:04 浏览: 51
以下是一个使用Spring Boot和Apache POI生成Excel报表的示例:
1. 添加依赖
在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
```
2. 创建实体类
创建一个实体类,用于存储报表数据。例如,如果要生成一个学生信息报表,可以创建一个名为Student的实体类:
```
public class Student {
private String name;
private int age;
private String gender;
// getters and setters
}
```
3. 创建报表生成服务
创建一个名为ExcelService的服务,用于生成报表。在该服务中,使用Apache POI创建Excel工作簿和工作表,并将数据写入单元格中:
```
@Service
public class ExcelService {
public void generateReport(List<Student> students, OutputStream outputStream) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Student Report");
// create header row
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("Name");
headerRow.createCell(1).setCellValue("Age");
headerRow.createCell(2).setCellValue("Gender");
// create data rows
int rowNum = 1;
for (Student student : students) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(student.getName());
row.createCell(1).setCellValue(student.getAge());
row.createCell(2).setCellValue(student.getGender());
}
// write to output stream
workbook.write(outputStream);
workbook.close();
}
}
```
4. 创建控制器
创建一个名为ExcelController的控制器,用于处理报表请求。在该控制器中,调用ExcelService生成报表,并将报表文件发送给客户端:
```
@RestController
public class ExcelController {
@Autowired
private ExcelService excelService;
@GetMapping("/students/report")
public void generateReport(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-disposition", "attachment; filename=student_report.xlsx");
List<Student> students = // get students from database or other sources
OutputStream outputStream = response.getOutputStream();
excelService.generateReport(students, outputStream);
outputStream.close();
}
}
```
5. 测试报表生成
启动Spring Boot应用程序,并访问http://localhost:8080/students/report。将生成一个名为student_report.xlsx的Excel报表文件,其中包含学生信息。