EasyExcel write file detailed explanation and source code analysis

When writing and exporting files, you will often see the following methods.

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

I saw the source code of EasyExcel read file import earlier, here is a quick look at the source code of EasyExcel write file export.

EasyExcel read file detailed explanation and source code analysis: https://blog.csdn.net/qq_42402854/article/details/131382629

Import dependencies:

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

1. EasyExcel write file source code

1. EasyExcelFactory factory class

Method: EasyExcel.write(file)

Check out the write() method:

insert image description here

The EasyExcel class calls the write method, which actually calls the method of the EasyExcelFactory class.

Check out the EasyExcelFactory class method:

insert image description here

The EasyExcelFactory factory class defines many overloaded methods for reading and writing. It mainly depends on the writing method, which can be divided into two categories:

  • Write Excel file, return ExcelWriterBuilder类.
  • Write to the sheet in the Excel file and return ExcelWriterSheetBuilder类.

From here we can see that the EasyExcelFactory factory class created the XxxBuilder class and returned the XxxBuilder class, so we can also directly use the XxxBuilder class to operate and write files.

2. ExcelWriterBuilder class

Check out the ExcelWriterBuilder class:

insert image description here

When the ExcelWriterBuilder class is instantiated, a WriteWorkbook object is created.

Check out the ExcelWriterBuilder class methods:

insert image description here

The ExcelWriterBuilder class mainly processes Excel files and related file attribute information, such as setting character encoding, file encryption passwords, ignoring which row of data to process, etc.

3. ExcelWriterSheetBuilder class

Check out the ExcelWriterSheetBuilder class:

insert image description here

When the ExcelWriterSheetBuilder class is instantiated, a WriteSheet object and an ExcelWriter object are created.

Check out the ExcelWriterSheetBuilder class method:

insert image description here

The ExcelWriterSheetBuilder class mainly processes each sheet information in the Excel file, such as setting the sheet name and index to be written.

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

4. ExcelWriter class

Check out the ExcelWriter class:

insert image description here

The ExcelWriter class contains the WriteWorkbook object and the processing of the WriteSheet object. In this way, each sheet information in the Excel file is processed.

View the ExcelWriter class method:

insert image description here

(1) How is the ExcelWriter class initialized?

When the ExcelWriterBuilder class calls the sheet() method, the ExcelWriter object is initialized.

When the ExcelWriterSheetBuilder class calls the doWrite method, the bottom layer traverses and writes each sheet information through the ExcelWriter object.

When initializing through the construction method in the respective XxxBuilder classes, the WriteWorkbook object and the WriteSheet object are created respectively, and then the assignment is completed in the respective build() methods of calling the sheet() method and the doWrite method respectively.

With the above knowledge, it is relatively simple to write Excel files through EasyExcel operations.

2. Write a sheet

In general, we create an object to establish a mapping relationship with the column names of the Excel file sheet.

Through @ExcelProperty @HeadRowHeight @ContentRowHeight等注解to define the table header, style, height and width and other information.

We create an export mapping object class, and construct the test data:

@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. Write once

    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. Write multiple times

    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);
            }
        }
    }

insert image description here

3. Write multiple sheets

Create another export mapping object class and construct test data:

@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. Write multiple sheet codes as follows:

    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);
                }

            }
        }
    }

insert image description here

4. Complicated header writing

Complex header and style information, set in the object class here, other operations are similar to the above. In general, it can meet business needs.

Create an export mapping object class, and construct the test data:

@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. The complex table header writing code is as follows:

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

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

insert image description here

For more operations, check the official document: https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write

– If you are hungry for knowledge, be humble if you are foolish.

Guess you like

Origin blog.csdn.net/qq_42402854/article/details/131434996