【工作中碰到Excel】EasyExcel读取Excel-1

开发环境:

SpringBoot2.7.6, JDK:8, EasyExcel:3.3.2

目标

读取得到Excel的所有内容
在这里插入图片描述

pom

!!注意这个地方EasyExcel需要去掉poi,自己引入

<!-- easyexcel -->
      <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>poi-ooxml-schemas</artifactId>
                    <groupId>org.apache.poi</groupId>
                </exclusion>
            </exclusions>
        </dependency>
<!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.2</version>
        </dependency>
<!-- lombok -->   
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
<!-- hutool -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.23</version>
      </dependency>
      </dependency>

实现方案1-无须指定sheet页

第一步-建立实体类

建一个实体类,将Excel中的内容映射到实体类
在EasyExcel提供的@ExcelProperty注解中将 value的属性值设置为对应的表头名称即可。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class FirstDemo {
    @ExcelProperty(value = "人名")
    private String fullName;

    @ExcelProperty(value = "性别")
    private String sex;

    @ExcelProperty(value = "出生日期")
    private Date birthDay;

    @ExcelProperty(value = "工资")
    private Long salary;

}

也可以通过index属性来进行标识

@ExcelProperty(index = 2)
    private Date birthDay;

第二步-编写读取代码

这种方式无法设置具体的sheet页,他会读取整个excel
代码如下:

public static void main(String[] args) {
        String excelPath = "excel路径";
        List<FirstDemo> firstDemos = EasyExcel
                .read(excelPath)
                .head(FirstDemo.class)
                .doReadAllSync();
        System.out.println(JSONUtil.toJsonPrettyStr(firstDemos));
    }

调用read方法,传入excel路径,
调用head方法,传入设置的实体类,
调用doReadAllSync读取文件。

结果如下:
在这里插入图片描述
ps:这个birthday是正确的,只是说打印成了时间戳的格式。

实现方案2-指定sheet页

如果像上一步的代码是无法指定sheet页的,会遍历所有的sheet页,我在上一份的excel中多加了一个sheet页,用上面的代码就会读取两个sheet页。
在这里插入图片描述
用上面的代码跑出的结果:
在这里插入图片描述

第一步-建立实体类

和方案1一致

@Data
@AllArgsConstructor
@NoArgsConstructor
public class FirstDemo {
    @ExcelProperty(value = "人名")
    private String fullName;

    @ExcelProperty(value = "性别")
    private String sex;

    @ExcelProperty(value = "出生日期")
    private Date birthDay;

    @ExcelProperty(value = "工资")
    private Long salary;

}

第二步-编写监听器

在这里需要定义EasyExcel的读取监听器。

public class FirstDemoListener extends AnalysisEventListener<FirstDemo> {

    private final List<FirstDemo> dataList = new ArrayList<FirstDemo>();

    public void invoke(FirstDemo data, AnalysisContext context) {
        dataList.add(data);
    }

    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("read finish");
    }

    public List<FirstDemo> getDataList() {
        return dataList;
    }
}

首先继承AnalysisEventListener,
现在我们需要实现的功能只需要重写这两个方法即可, invoke(), doAfterAllAnalysed(),
然后定义一个存储读取结果的List,
在invoke中将结果添加到list中,
最后设置一个这个list的get方法就齐活了。

第三步-编写读取代码

public static void main(String[] args) {
        String excelPath = "excel路径";
        FirstDemoListener firstDemoListener = new FirstDemoListener();
        EasyExcel.read(excelPath)
                .sheet(1)
                .headRowNumber(1)
                .head(FirstDemo.class)
                .registerReadListener(firstDemoListener)
                .doRead();

        List<FirstDemo> dataList = firstDemoListener.getDataList();
        System.out.println(JSONUtil.toJsonPrettyStr(dataList));
    }

在这里设置需要读取的sheet页【名称或第几个sheet页均可】,
设置第一行数据的index,
设置实体类信息,
注册监听器

之后通过之前在监听器中设置的list的get方法,即可获得数据。
在这里插入图片描述

### 如何使用 EasyExcel 读取 Excel 中插入的文件 在处理复杂的 Excel 文件时,可能会遇到需要读取嵌入对象的情况。然而,EasyExcel 主要专注于高效地解析和写入单元格中的常规数据(如字符串、数值等),对于读取嵌入的对象(比如图片或其他类型的附件)并不直接支持。 如果确实有需求获取这些附加资源,则可能需要借助其他库来实现完整的功能[^1]。例如,在某些场景下可以通过 Apache POI 来补充这一能力: ```java import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.util.List; public class EmbeddedFileReader { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("path/to/excel.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); // 获取工作簿内的所有内嵌对象列表 List<POIXMLRelation> relations = ((XSSFRelation[])workbook.getPackagePart().getRelationshipsByType( XSSFRelation.EMBEDDED_OBJECT RELATIONSHIP_TYPE))[0].getAllEmbedds(); for (POIXMLRelation relation : relations){ System.out.println(relation.getTargetURI()); } workbook.close(); fileInputStream.close(); } } ``` 上述代码展示了通过 Apache POI 库访问 Excel 文档内部存储的嵌入式文件路径的方式。需要注意的是这段代码仅作为概念验证用途,并未涵盖所有的边界情况以及错误处理逻辑;实际应用中应当更加严谨地对待文件 I/O 和异常捕获等问题[^2]。 当涉及到更复杂的需求时,建议评估是否有必要继续基于 EasyExcel 构建解决方案还是转向更适合特定任务的技术栈。另外值得注意的一点是,由于不同版本间的 API 可能存在差异,因此务必参照所使用的具体依赖项对应的官方文档来进行开发[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值