SpringBoot: Integrate EasyExcel to implement EasyExcel

1. EasyExcel

EasyExcel is a Java-based open source Excel operation tool, which provides a simple and powerful API, allowing developers to easily read, write, manipulate and generate Excel files.

EasyExcel supports the import and export of Excel files, can handle large amounts of data, and has high performance and low memory usage. It can read data in Excel files and convert the data into Java objects, and it can also write Java objects into Excel files.

EasyExcel also provides a wealth of formatting options and functions, such as setting cell styles, merging cells, setting formulas, etc. At the same time, EasyExcel also supports multi-threaded operations, which can improve processing efficiency when processing large amounts of data. Due to its simplicity and ease of use, EasyExcel is widely used in data import and export, report generation, data analysis and other fields.

illustrate Link
project address https://github.com/alibaba/easyexcel
Source code link https://www.yuque.com/easyexcel/doc/easyexcel

2. Commonly used annotations in EasyExcel

EasyExcel provides some commonly used annotations for identifying and controlling the behavior of fields during Excel reading and writing. The following are common annotations in EasyExcel:

@ExcelProperty: Used to identify fields in Excel. You can specify the column index or column name of the field in Excel. For example: @ExcelProperty("name"), @ExcelProperty(index = 0).

@ExcelIgnore: Used to identify fields that do not need to be imported or exported.

@ExcelIgnoreUnannotated: Used to identify whether fields not identified by the @ExcelProperty annotation are ignored.

@ExcelHead: used to identify the style of Excel table header. You can set the header height, font style, background color, etc.

@ExcelColumnWidth: used to set the width of Excel columns.

@ExcelDateTimeFormat: used to set formatting rules for date and time fields.

@ExcelBooleanFormat: used to set the display text of Boolean type fields in Excel.

@ExcelNumberFormat: used to set formatting rules for numeric fields.

These annotations can be combined according to actual needs to more flexibly control the behavior and style of fields during the Excel reading and writing process.

Insert image description here

3. Integrate EasyExcel

3.1 Introducing dependencies

To introduce EasyExcel dependencies, you need to add the following dependencies in your project's pom.xml file:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.3.0</version>
</dependency>

This will bring in the latest version of EasyExcel (currently 2.3.0). Students, please ensure that Maven is configured correctly and dependencies can be downloaded from the Maven repository. Once completed, Maven will automatically download and manage EasyExcel dependencies, as shown in the image below.

Insert image description here

3.2 Entity class definition

When using EasyExcel, entity classes need to be defined according to the following rules.

  • Entity classes need to add the @ExcelIgnoreUnannotated annotation to ensure that fields not marked by the @ExcelProperty annotation are ignored.
  • Use the @ExcelProperty annotation to mark fields that need to be read and written in Excel. You can specify the column index or column name of the field in Excel.
  • You can use other annotations (such as @ExcelDateTimeFormat, @ExcelNumberFormat, etc.) to further define the formatting rules of the field.

The following is a sample code that shows an entity class definition using EasyExcel to read and write Excel files:

@ExcelIgnoreUnannotated
public class Student {
    
    
    @ExcelProperty(index = 0)   // 列索引为0
    private String name;

    @ExcelProperty(index = 1)   // 列索引为1
    private int age;
    
    @ExcelProperty(index = 2)   // 列索引为2
    private String gender;
    
    @ExcelProperty(index = 3)   // 列索引为3
    private Date birthday;
    
    // Getters and Setters
    // ...
}

In the above code, the Student class defines 4 fields, which correspond to the 4 columns in the Excel file. By using the @ExcelProperty annotation and specifying the column index, we tell EasyExcel that these fields need to be mapped to the corresponding columns. Please note that this is just an example, you can define more fields and annotations according to your own needs to meet Excel reading and writing needs.

3.3 Custom converter

In EasyExcel, you can define a custom converter by implementing the Converter interface. The Converter interface has two generic parameters, representing the type when reading and the type when writing. Below is a simple example that shows how to implement the Converter interface to define a converter that converts a Boolean type to a string.

public class BooleanToStringConverter implements Converter<Boolean, String> {
    
    

    @Override
    public String convertToExcelData(Boolean value) {
    
    
        return value ? "是" : "否";
    }
    
    @Override
    public Boolean convertToJavaData(String value) {
    
    
        return "是".equals(value);
    }
}

In the above example, BooleanToStringConverter implements the Converter interface and implements the convertToExcelData() and convertToJavaData() methods. The convertToExcelData() method converts a Boolean type value to a string, and the convertToJavaData() method converts a string to a Boolean type value.

To use this converter when reading or writing Excel, you can associate the converter with the corresponding field through the @ExcelConverter annotation, the code is as follows.

@ExcelProperty(index = 0)
@ExcelConverter(BooleanToStringConverter.class)
private Boolean married;

In the above code, BooleanToStringConverter is specified as the converter of the field through the @ExcelConverter annotation, and EasyExcel will use this converter for data conversion when reading or writing Excel.

By implementing the Converter interface, you can define various custom converters to meet different types of data conversion needs.

Insert image description here

3.4 Write an export Excel interface

EasyExcel is a Java open source library that supports the export of Excel files. Through EasyExcel, students can easily export the data of Java objects to Excel files.

EasyExcel provides a rich API, which can configure the style, format and data content of the exported Excel. It is very flexible and easy to use. Students can use EasyExcel to export various types of data, including basic types, collections, custom objects, etc. At the same time, EasyExcel also supports the export of large amounts of data and can effectively handle the export operations of large batches of data.

In short, EasyExcel is a powerful and easy-to-use tool for exporting Excel. The following is a sample code that shows how to use EasyExcel to export the Excel interface. Please refer to it for reference.

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.util.ArrayList;
import java.util.List;

public class ExcelExportService {
    
    

    public void exportExcel(String filePath) {
    
    
        // 准备数据
        List<Student> studentList = prepareData();
    
        // 创建ExcelWriter对象
        ExcelWriter excelWriter = EasyExcel.write(filePath, Student.class).build();
    
        // 创建WriteSheet对象
        WriteSheet writeSheet = EasyExcel.writerSheet("学生信息").build();
    
        // 将数据写入Excel
        excelWriter.write(studentList, writeSheet);
    
        // 关闭ExcelWriter对象
        excelWriter.finish();
    }
    
    private List<Student> prepareData() {
    
    
        // 创建测试数据
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("张三", 18, "男"));
        studentList.add(new Student("李四", 20, "女"));
        studentList.add(new Student("王五", 19, "男"));
        return studentList;
    }
    
    public static void main(String[] args) {
    
    
        ExcelExportService excelExportService = new ExcelExportService();
        excelExportService.exportExcel("student.xlsx");
    }
}

In the above code, the ExcelExportService class encapsulates the interface for exporting Excel. In the exportExcel method, the data is first prepared and then an ExcelWriter object is created, which is used to write the Excel file. Next create a WriteSheet object to specify the name of the Sheet to be written. Finally, the data is written to Excel through the excelWriter.write method, and the writing operation is completed through the excelWriter.finish method.

In the prepareData method, a test data list containing student information is created. In the main method, the ExcelExportService object is created and the exportExcel method is called to export the Excel file. The exported Excel file name is student.xlsx. Students can modify the data and file paths according to actual needs to realize their own export function.

3.5 Write an import Excel interface

EasyExcel supports importing Excel files. With EasyExcel, you can easily read data from Excel files into Java objects. EasyExcel provides a rich API, which can configure the way to read Excel, the Sheet to be read, the number of rows to be read, etc. You can use EasyExcel to read various types of data, including basic types, collections, custom objects, etc.

At the same time, EasyExcel also supports the import of large amounts of data and can efficiently handle the import operations of large batches of data. EasyExcel also provides a listener mechanism, through which students can process and verify the read data. In short, EasyExcel is a powerful and easy-to-use tool for importing Excel.

The following is a sample code that shows how to use EasyExcel to import the Excel interface.

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import java.util.List;

public class ExcelImportService {
    
    

    public void importExcel(String filePath) {
    
    
        // 创建Excel读取监听器
        ReadListener<Student> listener = new ExcelReadListener();
        // 创建读取Sheet配置
        ReadSheet readSheet = EasyExcel.readSheet(0).registerReadListener(listener).build();
        // 执行读取操作
        EasyExcel.read(filePath, Student.class).build().read(readSheet);
        // 获取读取的数据
        List<Student> studentList = ((ExcelReadListener) listener).getStudentList();
        // 处理读取的数据
        processImportedData(studentList);
    }
    
    private void processImportedData(List<Student> studentList) {
    
    
        // 处理导入的数据
    }
    
    public static void main(String[] args) {
    
    
        ExcelImportService excelImportService = new ExcelImportService();
        excelImportService.importExcel("student.xlsx");
    }
}

In the above code, the ExcelImportService class encapsulates the interface for importing Excel. In the importExcel method, first create the Excel read listener ExcelReadListener, which is used to process the read data. Then create a ReadSheet configuration ReadSheet, and register the listener to the read configuration through the registerReadListener method. Next, use EasyExcel to perform the reading operation and hand over the read data to the listener for processing. Finally, the imported data is processed through the `processImportedData method.

In the main method, the ExcelImportService object is created and the importExcel method is called to import the Excel file. The imported Excel file is named student.xlsx. Students can modify the file path and data processing logic according to actual needs to realize their own import function.

Insert image description here

4. Summary

This article explains how to integrate EasyExcel in the SpringBoot project, realize Excel quick import and export, analyze the implementation process of Excel import and export, and provide relevant source code

Guess you like

Origin blog.csdn.net/zhanggqianglovec/article/details/132106812