Apache POI 实现 Excel 表格下载

这里以苍穹外卖中数据导出功能为例,记录下 Apache POI 导出 Excel 表格的过程。

首先在 pom.xml 中导入相关依赖

xml 复制代码
<!-- poi 用于操作 excel 表格-->
<dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
 </dependency>

controller层

注意方法中的参数 response, service层定义输出流对象要用。

java 复制代码
@RestController
@RequestMapping("/admin/report")
@Slf4j
public class ReportController {
	@GetMapping("/export")
	@ApiOperation("/导出运营报表")
	public void exportExcel(HttpServletResponse response){
	// 注意这里的参数 response, service层定义输出流对象要用。
	    reportService.exportExcel(response);
	}
}

Service层

定义输出流对象时要用 response 去定义,不是直接 new FileOutputStream()

在得到模板文件时候,注意新建的文件夹在resource下,不要写错,刚开始定义的文件夹名字叫 template, 没加字母 's',一直获取不到模板文件,正确的应该叫 templates

java 复制代码
@Service
public class ReportServiceImpl implements ReportService {
		@Override
	    public void exportExcel(HttpServletResponse response) {
	        // 得到最近三十天的起止日期
	        LocalDate beginTime = LocalDate.now().minusDays(30);
	        LocalDate endTime = LocalDate.now().minusDays(1);
	        BusinessDataVO businessDataVo = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MAX));
	
	        // 得到模板文件
	        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");
	
	        try {
	            XSSFWorkbook excel = new XSSFWorkbook(in);
	            // 写入时间
	            XSSFSheet sheet = excel.getSheetAt(0);
	            sheet.getRow(1).getCell(1).setCellValue("时间:" + beginTime + "~" + endTime);
	
	            // 写入概览数据
	            sheet.getRow(3).getCell(2).setCellValue(businessDataVo.getTurnover());
	            sheet.getRow(3).getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
	            sheet.getRow(3).getCell(6).setCellValue(businessDataVo.getNewUsers());
	            sheet.getRow(4).getCell(2).setCellValue(businessDataVo.getValidOrderCount());
	            sheet.getRow(4).getCell(4).setCellValue(businessDataVo.getUnitPrice());
	
	            // 填充明细数据
	            for (int i = 0; i < 30; i++) {
	                LocalDate date = beginTime.plusDays(i);
	                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
	                XSSFRow row = sheet.getRow(7 + i);
	                row.getCell(1).setCellValue(date.toString());
	                row.getCell(2).setCellValue(businessData.getTurnover());
	                row.getCell(3).setCellValue(businessData.getValidOrderCount());
	                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
	                row.getCell(5).setCellValue(businessData.getUnitPrice());
	                row.getCell(6).setCellValue(businessData.getNewUsers());
	            }
	
	            // 输出流下载文件
	            ServletOutputStream out = response.getOutputStream();
	            excel.write(out);
	
	            // 关闭资源
	            out.flush();
	            out.close();
	            excel.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                in.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
    }

实现效果

相关推荐
沉到海底去吧Go9 小时前
【工具教程】PDF电子发票提取明细导出Excel表格,OFD电子发票行程单提取保存表格,具体操作流程
pdf·excel
黑客老李10 小时前
JavaSec | SpringAOP 链学习分析
java·运维·服务器·开发语言·学习·apache·memcached
开开心心就好11 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
临水逸16 小时前
可视化大屏工具对比:GoView、DataRoom、积木JimuBI、Metabase、DataEase、Apache Superset 与 Grafana
apache·grafana
SelectDB技术团队16 小时前
Apache Doris + MCP:Agent 时代的实时数据分析底座
人工智能·数据挖掘·数据分析·apache·mcp
田猿笔记16 小时前
Apache DolphinScheduler 和 Apache Airflow 对比
apache
酷爱码16 小时前
在 Linux 中修改 Apache HTTP Server(httpd)默认端口的完整指南
linux·http·apache
学习HCIA的小白16 小时前
Apache Druid
apache
沉到海底去吧Go1 天前
【行驶证识别成表格】批量OCR行驶证识别与Excel自动化处理系统,行驶证扫描件和照片图片识别后保存为Excel表格,基于QT和华为ocr识别的实现教程
自动化·ocr·excel·行驶证识别·行驶证识别表格·批量行驶证读取表格
Abigail_chow2 天前
EXCEL如何快速批量给两字姓名中间加空格
windows·microsoft·excel·学习方法·政务