2026.3.10 Apache POI的学习及思考

2026.3.10 Apache POI

介绍

Apache POI(Poor Obfuscation Implementation 可怜的混淆实现)是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说,我们可以使用POI在Java程序中对Miscrosoft Office各种文件进行读写操作。

一般情况下,POI都是用于操作Excel文件。

应用场景

  • 银行网银系统导出交易明细
  • 各种业务系统导出Excel报表
  • 批量导入业务数据

入门案例

通过POI写Excel文件

导入坐标
xml 复制代码
<!--这是Apache POI的核心库,主要负责处理老版本(Office 97-2003)的二进制文件格式-->
<dependency>
	<groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>
<!--这个包是为了支持新版本(Office2007及以上)的文件格式而设计的-->
<dependency>
	<groupId>org.apache.poi</groupId>
    <artifactId>poi--ooxml</artifactId>
    <version>3.16</version>
</dependency>
编写代码
java 复制代码
public class POITest{
    /**
     * 通过POI创建Excel文件并且写入文件内容
     */
    public static void write() throws IOException {
        //在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();
        //在Excel中创建一个Sheet页
        XSSFSheet sheet = excel.createSheet("info");
        //在Sheet页中创建行对象,传入的rownum:1,代表excel的两行
        XSSFRow row = sheet.createRow(1);
        //从该行第2个单元格,写入文件内容
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("城市");

        //创建一个新行
        row = sheet.createRow(2);
        row.createCell(1).setCellValue("张三");
        row.createCell(2).setCellValue("北京");

        //创建一个新行
        row = sheet.createRow(3);
        row.createCell(1).setCellValue("李四");
        row.createCell(2).setCellValue("上海");

        //通过输出流将内存中的excel文件写入到磁盘
        FileOutputStream out = new FileOutputStream(new File("E:\\aaabigproject\\software\\test\\info.xlsx"));
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();
    }

    public static void main(String[] args) throws IOException {
        write();
    }
}
获得结果

j

通过POI读取Excel文件内容

java 复制代码
/**
     * 通过POI读取Excel文件中的内容
     * @throws Exception
     */
    public static void read() throws Exception{
        FileInputStream in = new FileInputStream(new File("E:\\aaabigproject\\software\\test\\info.xlsx"));
        //读取磁盘上已存在的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //读取Excel文件中的第一个Sheet页
        XSSFSheet sheet = excel.getSheetAt(0);
        //获取Sheet页中最后一行的行号,数字从0开始
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            //获得某一行
            XSSFRow row = sheet.getRow(i);
            //获得单元格对象
            String cellValue = row.getCell(1).getStringCellValue();
            String cellValue1 = row.getCell(2).getStringCellValue();
            System.out.println(cellValue + " " + cellValue1);
        }
        
        in.close();
        excel.close();
    }

    public static void main(String[] args) throws Exception {
        read();
    }
text 复制代码
姓名 城市
张三 北京
李四 上海

导出运营数据Excel报表

业务规则:

  • 导出Excel形式的报表文件
  • 导出最近30天的运营数据

代码开发

在一般业务开发中,如果要导出复杂形式的的Excel表格,我们会先利用图形界面设计该表格的格式,而后在程序里读取该模板文件,在相应的空白处填入相应数字。

实现步骤:

  1. 设计Excel模板文件
  2. 查询近30天的运营数据
  3. 将查询到的运营数据写入模板文件
  4. 通过输出流将Excel文件下载到客户端浏览器

Controller

java 复制代码
/**
     * 导出运营数据报表
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("导出运营数据报表")
    public void export(HttpServletResponse response){
        reportService.exportBusinessData(response);
    }

Service

java 复制代码
/**
     * 导出运营数据报表
     * @param response
     */
    void exportBusinessData(HttpServletResponse response);

ServiceImpl

java 复制代码
/**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库,获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                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());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
相关推荐
web前端神器18 小时前
记录uniapp小程序的报错
小程序·uni-app·apache
一條狗19 小时前
学习日报 20260423|Vue SPA 部署到 Spring Boot:404/500 错误排查与解决方案1
vue.js·spring boot·学习
炽烈小老头19 小时前
【每天学习一点算法 2026/04/23】盛最多水的容器
学习·算法
寒秋花开曾相惜19 小时前
(学习笔记)4.1 Y86-64指令集体系结构(4.1.6 一些Y86-64指令 )
linux·运维·服务器·开发语言·笔记·学习·安全
蓝桉~MLGT19 小时前
Ai-Agent学习历程—— Harness和Memory介绍和应用 & vibe Coding工具选择
人工智能·学习
GHL28427109019 小时前
LangChain学习
学习·ai·langchain
知识分享小能手19 小时前
ECharts入门学习教程,从入门到精通,综合实战——ECharts电商数据可视化完整知识点+案例代码(8)
学习·信息可视化·echarts
噜噜噜阿鲁~20 小时前
python学习笔记 | 7.2、高级特性-迭代
笔记·python·学习
AI算法沐枫20 小时前
从客服转行AI Agent:半年学习与求职复盘
人工智能·深度学习·学习·大模型·agent·智能体·ai应用开发
在学了加油20 小时前
ResNet50V2学习笔记
笔记·学习