内容纲要

环境

  • Java
  • Spring框架
  • Gradle

概述

EasyExcel是一个基于Java的Excel文件处理工具,在POI的基础上进行了一定的重写,减少了内存的消耗。

具体参考官方文档:https://easyexcel.opensource.alibaba.com/docs/current/

准备

implementation 'com.alibaba:easyexcel:3.2.0'

使用示例

读取Excel内的数据

  1. 准备Excel

  1. 自定义Excel行数据的对象

使用@ExcelProperty注解可以指定该字段映射为Excel中第几列的数据。在下述示例中:第一列【序号】的数据会被映射为id,第二列【姓名】的数据会被映射为name,第三列【性别】的数据会被映射为gender。

@Data
public class ExcelData {
    @ExcelProperty(index = 0)
    private String id;
    @ExcelProperty(index = 1)
    private String name;
    @ExcelProperty(index = 2)
    private String gender;
}
  1. 自定义ReadListener
@Slf4j
public class ExcelReadListener implements ReadListener<ExcelData> {
    @Override
    public void invoke(ExcelData data, AnalysisContext context) {
        String name = data.getName();
        if (Strings.isEmpty(name)) {
            throw new RuntimeException(String.format("第%s行姓名为空", context.readRowHolder().getRowIndex() + 1));
        }
        log.info(String.format("success read value of name %s", data.getName()));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
            //在这里可以做一些持久化的事情,当excel解析完成后直接落库。
    }
}
  1. 使用自定义的ReadListener完成对Excel的解析并log对应数据
@Test
void test_read_excel() {
  File file = new File("src/main/resources/test.xlsx");
  EasyExcel.read(file, ExcelData.class, new ExcelReadListener())
                .sheet()
                .headRowNumber(1)
                .doRead();
}

在执行测试后结果为:

可以看到成功读取了Excel中的内容,同时跳过了表头的内容。这是因为headRowNumber(1)指定了表头为1行,若存在多行表头情况可以调整对应的数据以跳过表头数据的解析。

写入Excel

  1. 自定义Excel行数据的对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExportData {
    @ExcelProperty(value = "学号", index = 0)
    private String id;
    @ExcelProperty(value = "姓名", index = 1)
    private String name;
    @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
    @ExcelProperty(value = "生成日期", index = 2)
    private Date createdTime;
}

在此示例中,【生成日期】是一个时间格式的字段,用EasyExcel包中的@DateTimeFormat进行注解来定义格式化时间的格式。需要注意的是该注解仅能生效在Date类型的字段上,无法使用LocalDateTime

  1. 使用EasyExcel生成Excel文档
@Test
void test_export_excel() {
  File file = new File("src/main/resources/export.xlsx");
  EasyExcel.write(file, ExportData.class)
    .sheet("test")
    .doWrite(
    List.of(
      new ExportData("20240301", "Tony", new Date()),
      new ExportData("20240302", "Chris", new Date()),
      new ExportData("20240303", "Amy", new Date())
    )
  );
}

生成的文档内容如下:

最后修改日期: 2024年1月21日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。