苍穹外卖项目日记(day12)
苍穹外卖|项目日记(day12)
前言: 今天的任务相对简单, 主要是熟悉一下在项目中操作Excel报表, 感觉挺简单的, 很多方法都封装好了.
总结: 今天是后端的完结, 不过还需努力, 这个项目只是入门, 还需要独自做一个项目才算初有成果,微服务, 408, 诺伊, ai都等着我呢
今日收获:
1.Apach POI(Excel)的入门使用
一.Apach POI(Excel)的入门使用
1. 基本概念
Apache POI 包含多个组件,其中处理 Excel 的主要有:
- HSSF - 处理 Excel 97-2003 格式 (.xls)
- XSSF - 处理 Excel 2007 及以上格式 (.xlsx)
- SXSSF - XSSF 的流式 API,适用于大数据量
2. 在项目中导入依赖
<!-- 基础 POI -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.3</version>
</dependency>
<!-- XSSF 支持 -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version>
</dependency>
3.项目中使用
需填写数据的Excel图片:
代码示例:
@Overridepublic void export(HttpServletResponse response) {// 1.查询数据库, 获取营业数据---查询最近30天的运营数据LocalDate begin = LocalDate.now().minusDays(30);LocalDate end = LocalDate.now().minusDays(1);LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);// 概览数据BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);// 2. 通过POI将数据写入到Excel文件中InputStream InStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");try {XSSFWorkbook workbook = new XSSFWorkbook(InStream);XSSFSheet sheet = workbook.getSheetAt(0);// 第二行XSSFRow row1 = sheet.getRow(1);row1.getCell(1).setCellValue("时间:"+begin+"至"+end);// 第四行 概览数据填写XSSFRow row3 = sheet.getRow(3);row3.getCell(2).setCellValue(businessData.getTurnover());row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());row3.getCell(6).setCellValue(businessData.getNewUsers());// 第五行, 概览数据填写XSSFRow row4 = sheet.getRow(4);row4.getCell(2).setCellValue(businessData.getValidOrderCount());row4.getCell(4).setCellValue(businessData.getUnitPrice());// 填入明细数据for (int i = 0; i < 30; i++) {LocalDate date = begin.plusDays(i);BusinessDataVO datadetail = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));XSSFRow detail_row = sheet.getRow(7 + i);detail_row.getCell(1).setCellValue(date.toString());detail_row.getCell(2).setCellValue(datadetail.getTurnover());detail_row.getCell(3).setCellValue(datadetail.getValidOrderCount());detail_row.getCell(4).setCellValue(datadetail.getOrderCompletionRate());detail_row.getCell(5).setCellValue(datadetail.getUnitPrice());detail_row.getCell(6).setCellValue(datadetail.getNewUsers());}// 3. 通过输出流将Excel文件下载到客户端浏览器ServletOutputStream outputStream = response.getOutputStream();workbook.write(outputStream);workbook.close();outputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}
完结撒花!!!