Apache POI

Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。

业务场景:导入Excel文件内数据到数据库内、把数据库内的数据导出为Excel报表。

maven坐标

java 复制代码
        <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文件示例

java 复制代码
@Test
    public void testApachePOI(){
        //在内存中创建一个Excel对象
        XSSFWorkbook excel = new XSSFWorkbook();
        //创建Shell页
        XSSFSheet sheet = excel.createSheet("itcast");
        //在Sheet页中创建行,0为第一行,关于ApachePOI的行和列都是从0开始
        XSSFRow row = sheet.createRow(0);
        //创建单元格,0为第一列
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("年龄");
        //创建数据行
        XSSFRow dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue(1);
        dataRow.createCell(1).setCellValue("张三");
        dataRow.createCell(2).setCellValue(18);
        //创建数据行
        XSSFRow dataRow2 = sheet.createRow(2);
        dataRow2.createCell(0).setCellValue(2);
        dataRow2.createCell(1).setCellValue("张四");
        dataRow2.createCell(2).setCellValue(19);
        //创建输出流,指定路径
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("D:\\excel\\test.xlsx");
            excel.write(out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (excel != null){
                try {
                    excel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

文档

读取excel的数据

java 复制代码
@Test
    public void testApachePOI2() throws Exception{
        FileInputStream in = new FileInputStream("D:\\excel\\test.xlsx");
        //通过输入流读取指定的文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取第一个Sheet页
        XSSFSheet sheet = excel.getSheetAt(0);
        int LastRowNum = sheet.getLastRowNum();
        for (int i = 0; i <= LastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if (i==0){
                System.out.println(row.getCell(0).getStringCellValue()+","+row.getCell(1).getStringCellValue()+","+row.getCell(2).getStringCellValue());
            }
            else {
                System.out.println(row.getCell(0)+","+row.getCell(1).getStringCellValue()+","+row.getCell(2));
            }
        }
        in.close();
        excel.close();
    }

实战:在用报表模板创建三十天营业额统计

Controller层

java 复制代码
 @GetMapping("/export")
    @ApiOperation("导出数据")
    public Result exportData(HttpServletResponse  response){
        log.info("开始导出数据...");
        reportService.exportData(response);
        return null;
    }

Service层

java 复制代码
  /**
     * 导出近30天的运营数据报表
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        LocalDate now = LocalDate.now();
        LocalDate begin = now.minusDays(30);
        LocalDate end = now.minusDays(1);
        //查询运营数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX));
        //读取模板,将其作为输入流读取到内存中
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获取第四行
            XSSFRow row4 = sheet.getRow(3);
            row4.getCell(2).setCellValue(businessDataVO.getTurnover());
            row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第五行
            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //明细数据
            for (int i=0;i<30;i++){
                LocalDate date = begin.plusDays(i);
                businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //通过输出流进行文件下载到客户端服务器中
            OutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

模板放在

所以可以通过获取类->获取类加载器->获取resource->路径获得。

BusinessDataVO

java 复制代码
package com.sky.vo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 数据概览
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BusinessDataVO implements Serializable {

    private Double turnover;//营业额

    private Integer validOrderCount;//有效订单数

    private Double orderCompletionRate;//订单完成率

    private Double unitPrice;//平均客单价

    private Integer newUsers;//新增用户数

}

模板

导出示例

补充:

HttpServletResponse 属于 Java Servlet API 框架的一部分。

框架介绍

所属框架: Java Servlet API(Java EE/Web容器标准API)

作用: 用于处理HTTP响应的核心接口

相关方法说明

在当前代码中使用的 HttpServletResponse 方法包括:

getOutputStream() - 获取响应的输出流,用于向客户端发送二进制数据(如Excel文件)

setContentType() - 设置响应内容类型(MIME类型)

setHeader() - 设置HTTP响应头信息

相关推荐
vortex512 小时前
基于 Apache 规则拦截目录扫描器请求:实测与配置指南
linux·网络安全·apache
观望过往12 小时前
Apache IoTDB 连续查询(CQ)全解析
apache·iotdb
世界尽头与你14 小时前
CVE-2020-1938_ Apache Tomcat AJP 文件读取与包含漏洞
java·网络安全·渗透测试·tomcat·apache
SelectDB技术团队14 小时前
Apache Doris 在小米统一 OLAP 和湖仓一体的实践
数据仓库·数据分析·apache·数据库开发
过往记忆15 小时前
Apache XTable:打破数据湖格式孤岛的“通用翻译官”
apache
耿雨飞15 小时前
Apache Airflow 第四章:生态扩展与插件开发
apache·airflow
渣渣盟1 天前
Flink数据流高效写入HBase实战
大数据·flink·scala·apache·hbase
n***84072 天前
防火墙安全策略(基本配置)
服务器·php·apache
顧棟2 天前
Apache POI导出出现FontConfiguration中NULL
apache
FreeBuf_2 天前
高危警报:Apache Kvrocks ‘RESET‘ 命令漏洞可获取管理员权限
apache