一.什么是Apache POI
通过Java代码就可以读写Microsoft Office各种文档的开源项目, 一般情况下,POI 都是用于操作 Excel 文件。
二.实现步骤
-
导入Apache POI的maven坐标:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> -
设计Excel模板文件并导入, 一般放在resource下的template文件夹中
3). 查询相关数据
3). 将查询到的数据写入模板文件
4). 通过输出流将Excel文件下载到客户端浏览器
代码举例:
/**
* 导出运营数据Excel报表
* @param response
*/
@Override
public void exportBusinessData(HttpServletResponse response) {
//访问数据→BusinessDataVO
LocalDate begin = LocalDate.now().minusDays(30);
LocalDate end = LocalDate.now().minusDays(1);
BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
//注意后缀不要忘了
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
//write
try {
XSSFWorkbook excel= new XSSFWorkbook(inputStream);
XSSFSheet sheet = excel.getSheet("Sheet1");
sheet.getRow(1).getCell(1).setCellValue((begin + "至" + end);
sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
//明细数据
for (int i = 0; i < 30; i++) {
BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
XSSFRow row = sheet.getRow(7 + i);
row.getCell(1).setCellValue(begin.toString());
row.getCell(2).setCellValue(data.getTurnover());
row.getCell(3).setCellValue(data.getValidOrderCount());
row.getCell(4).setCellValue(data.getOrderCompletionRate());
row.getCell(5).setCellValue(data.getUnitPrice());
row.getCell(6).setCellValue(data.getNewUsers());
begin.plusDays(1);
//通过输出流将Excel文件下载到客户端浏览器
}
ServletOutputStream outputStream = response.getOutputStream();
excel.write(outputStream);
//关闭资源
outputStream.close();
excel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}