EasyExcel写入文件详解和源码分析

写入文件导出的话,经常会看到下面这些方法。

EasyExcel.write(fileName)
                .head(DemoData.class) //指定写用哪个class去写
                .sheet() //指定Sheet名。为空时默认0。
                .doWrite(getDemoData());

前面看了 EasyExcel读取文件导入的源码,这里就快速过一下 EasyExcel写入文件导出的源码。

EasyExcel读文件详解和源码分析:https://blog.csdn.net/qq_42402854/article/details/131382629

引入依赖:

        <!--   easyexcel 3.1.0+版本不需要poi依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.1</version>
        </dependency>

一、EasyExcel写入文件源码

1、EasyExcelFactory工厂类

方法:EasyExcel.write(file)

查看 write()方法:

在这里插入图片描述

EasyExcel类调用 write方法,实际调用的是 EasyExcelFactory类的方法。

查看 EasyExcelFactory类方法:

在这里插入图片描述

EasyExcelFactory工厂类定义了许多读和写的重载方法。主要看写方法,分为两类:

扫描二维码关注公众号,回复: 16064617 查看本文章
  • 写入Excel文件,返回 ExcelWriterBuilder类
  • 写入Excel文件中的sheet,返回 ExcelWriterSheetBuilder类

从这里我们可以看出,EasyExcelFactory工厂类创建了 XxxBuilder类,并返回了 XxxBuilder类,那是不是我们也可以直接使用 XxxBuilder类操作写文件。

2、ExcelWriterBuilder类

查看 ExcelWriterBuilder类:

在这里插入图片描述

ExcelWriterBuilder类实例化时,创建了 WriteWorkbook对象。

查看 ExcelWriterBuilder类方法:

在这里插入图片描述

ExcelWriterBuilder类主要处理 Excel文件和相关文件属性信息,比如设置 字符编码、文件加密的密码,忽略处理哪行数据等。

3、ExcelWriterSheetBuilder类

查看 ExcelWriterSheetBuilder类:

在这里插入图片描述

ExcelWriterSheetBuilder类实例化时,创建了 WriteSheet对象和 ExcelWriter对象。

查看 ExcelWriterSheetBuilder类方法:

在这里插入图片描述

ExcelWriterSheetBuilder类主要处理 Excel文件中的每一个 sheet信息,比如设置要写入的sheet名,索引。

调用 doWrite方法其实底层通过 ExcelWriter对象写入每一个 sheet信息。

4、ExcelWriter类

查看 ExcelWriter类:

在这里插入图片描述

ExcelWriter类包含了 WriteWorkbook对象和对 WriteSheet对象的处理。从而处理 Excel文件中的每一个 sheet信息。

查看 ExcelWriter类方法:

在这里插入图片描述

(1)ExcelWriter类是如何初始化的?

在 ExcelWriterBuilder类调用 sheet()方法时,初始化了 ExcelWriter对象。

在 ExcelWriterSheetBuilder类调用 doWrite方法时,底层通过 ExcelWriter对象遍历写入每一个 sheet信息。

在各自的XxxBuilder类中通过构造方法初始化时,分别创建的 WriteWorkbook对象和 WriteSheet对象,然后分别在调用 sheet()方法和 doWrite方法各自的 build()方法中完成赋值的。

有个上面的知识,接下来通过 EasyExcel操作写入 Excel文件就比较简单了。

二、写入一个sheet

一般情况,我们创建一个对象来和 Excel文件 sheet的列名建立映射关系。

通过 @ExcelProperty @HeadRowHeight @ContentRowHeight等注解来定义表头,样式,高宽等信息。

我们创建一个导出映射对象类,并构造测试数据:

@Getter
@Setter
@EqualsAndHashCode
@ColumnWidth(20)   // 列宽,也可以针对每列使用
@HeadRowHeight(25) // 表头行高
@ContentRowHeight(15) // 内容行高
public class DemoData {
    
    

    /**
     * @ExcelProperty注解 </br>
     * value - 设置表头名
     * index - 设置表头所属的列名,索引从0开始, 如果下面index不连续,那么就会保留不存在index列为空列。
     */
    @ExcelProperty(value = "标题", index = 0)
    private String string;

    /**
     * @DateTimeFormat注解 日期格式化
     */
    @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
    @ExcelProperty(value = "日期", index = 1)
    @ColumnWidth(30)   // 列宽
    private Date date;

    @ExcelProperty(value = "浮点数据", index = 2)
    private Double doubleData;

    /**
     * @ExcelIgnore注解 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;

}
    private static List<DemoData> getDemoData() {
    
    
        List<DemoData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
    
    
            DemoData data = new DemoData();
            data.setString("字符串" + (i + 1));
            data.setDate(new Date());
            data.setDoubleData(0.565 * i);
            data.setIgnore("setIgnore");
            list.add(data);
        }
        return list;
    }

1、一次写入

    private static void oneSheetWrite1() {
    
    
        String fileName = "D:\\TempFiles\\export表格.xlsx";

        // 注意:在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照方法2,重复多次写入。
        // 方法1: 一次写到同一个sheet
        EasyExcel.write(fileName)
                .head(DemoData.class) //指定写用哪个class去写
                .sheet() //指定Sheet名。为空时默认0。
                .doWrite(getDemoData());
    }

2、多次写入

    private static void oneSheetWrite2() {
    
    
        String fileName = "D:\\TempFiles\\export表格.xlsx";

        // 方法2: 多次写到同一个sheet
        try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
    
    
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet模板").build();

            // 这里调用了五次写入,实际使用时也根据数据库分页的总的页数来分页去数据库查询数据
            for (int i = 0; i < 5; i++) {
    
    
                List<DemoData> demoDataList = getDemoData();
                excelWriter.write(demoDataList, writeSheet);
            }
        }
    }

在这里插入图片描述

三、写入多个sheet

再创建一个导出映射对象类,并构造测试数据:

@Getter
@Setter
@EqualsAndHashCode
@ColumnWidth(20)   // 列宽,也可以针对每列使用
@HeadRowHeight(25) // 表头行高
@ContentRowHeight(15) // 内容行高
public class DemoData2 {
    
    

    /**
     * @ExcelProperty注解 </br>
     * value - 设置表头名
     * index - 设置表头所属的列名,索引从0开始, 如果下面index不连续,那么就会保留不存在index列为空列。
     */
    @ExcelProperty(value = "标题", index = 0)
    private String string;

    /**
     * @DateTimeFormat注解 日期格式化
     */
    @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
    @ExcelProperty(value = "日期", index = 1)
    @ColumnWidth(30)   // 列宽
    private Date date;

    @ExcelProperty(value = "浮点数据", index = 2)
    private Double doubleData;

    @ExcelProperty(value = "整数", index = 3)
    private Integer integerData;

    /**
     * Java BigDecimal|Double类型类型导出丢失精度,使用 @NumberFormat("#.############")时,0.0会显示.符号。
     * 建议定义为 String类型
     */
    @ExcelProperty(value = "经度", index = 4)
    private String longitude;

    @ExcelProperty(value = "纬度", index = 5)
    private String latitude;

}
    private static List<DemoData2> getDemoData2() {
    
    
        List<DemoData2> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
    
    
            DemoData2 data = new DemoData2();
            data.setString("字符串" + (i + 1));
            data.setDate(new Date());
            data.setDoubleData(0.565 * i);
            data.setIntegerData(i + 1);
            data.setLongitude(String.valueOf(123.400124005395 * i));
            data.setLatitude(String.valueOf(42.4912142139705 * i));
            list.add(data);
        }
        return list;
    }

1、写入多个sheet代码如下:

    private static void manySheetWrite() {
    
    
        String fileName = "D:\\TempFiles\\export表格2.xlsx";
        try (ExcelWriter excelWriter = EasyExcel.write(fileName).build()) {
    
    
            for (int i = 0; i < 5; i++) {
    
    
                if (i % 2 == 0) {
    
    
                    WriteSheet writeSheet = EasyExcel.writerSheet("sheet模板DemoData-" + (i + 1)).head(DemoData.class).build();
                    List<DemoData> demoDataList = getDemoData();
                    excelWriter.write(demoDataList, writeSheet);
                } else {
    
    
                    WriteSheet writeSheet = EasyExcel.writerSheet("sheet模板DemoData2-" + (i + 1)).head(DemoData2.class).build();
                    List<DemoData2> demoData2List = getDemoData2();
                    excelWriter.write(demoData2List, writeSheet);
                }

            }
        }
    }

在这里插入图片描述

四、复杂表头写入

复杂表头和样式信息,这里设置在对象类中,其他操作和上面类似。一般情况,可以满足业务需要。

创建一个导出映射对象类,并构造测试数据:

@Getter
@Setter
@EqualsAndHashCode
@ColumnWidth(20)   // 列宽,也可以针对每列使用
@HeadRowHeight(25) // 表头行高
@ContentRowHeight(33) // 内容行高
// 头背景设置成红色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 10)
public class ComplexHeadDemoData {
    
    

    /**
     * @ExcelProperty注解 </br>
     * value - 设置表头名, {}, 有一个以上的表头信息时,它会自动合并
     */
    @ExcelProperty(value = {
    
    "主标题", "标题"}, index = 0)
    // 字符串的内容样式
    @ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    @ContentFontStyle(fontHeightInPoints = 18)
    private String string;

    /**
     * @DateTimeFormat注解 日期格式化
     */
    @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
    @ExcelProperty(value = {
    
    "主标题", "日期"}, index = 1)
    @ColumnWidth(30)   // 列宽
    private Date date;

    @ExcelProperty(value = {
    
    "主标题", "浮点数据", "head"}, index = 2)
    private Double doubleData;

    /**
     * @ExcelIgnore注解 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;

}
    private static List<ComplexHeadDemoData> getComplexHeadDemoData() {
    
    
        List<ComplexHeadDemoData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
    
    
            ComplexHeadDemoData data = new ComplexHeadDemoData();
            data.setString("字符串" + (i + 1));
            data.setDate(new Date());
            data.setDoubleData(0.565 * i);
            data.setIgnore("setIgnore");
            list.add(data);
        }
        return list;
    }

1、复杂表头写入代码如下:

    private static void complexHeadDemoDataSheetWrite() {
    
    
        String fileName = "D:\\TempFiles\\export表格.xlsx";

        EasyExcel.write(fileName)
                .head(ComplexHeadDemoData.class)
                .sheet("sheet模板")
                .doWrite(getComplexHeadDemoData());
    }

在这里插入图片描述

更多操作查看官方文档:https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write

– 求知若饥,虚心若愚。

猜你喜欢

转载自blog.csdn.net/qq_42402854/article/details/131434996