Unfixed column excel import and export, with source code

A series of work came

preface

We briefly introduce the practice scheme of excel import and export technology. At present, the most used open source frameworks mainly include the following three categories:
1/ apache poi: poi is the most widely used import and export framework, but its disadvantages are also obvious. When exporting a large amount of data, it is easy to oom
2/ easypoi: the bottom layer of easypoi is also developed in depth based on apache poi. Its main feature is to simplify more repetitive work and avoid writing repetitive code. The most significant feature is that it has rich export support
3/ easyexcel: easyexcel is an open source excel parsing tool from Alibaba. The underlying logic is also secondary developed based on apache poi. At present, it is also widely used

In general, both easypoi and easyexcel are secondary development based on apache poi.

Tip: the following is the main content of this article. The following cases can be used for reference

1, What are the differences between easypoi and easyexcel and apache poi?

1. When reading and writing data, easypoi gives priority to writing the data into the memory first, so the reading and writing performance is very high. This operation will not cause any problems when it is usually used, but oom will appear when there is a large amount of data. Of course, it also provides sax mode line by line parsing, which needs to be implemented according to the current scene.
2. easyexcel is parsed line by line based on sax mode by default, which significantly reduces the memory and will not cause oom. The program has high concurrency scenario verification, so the overall operation is relatively stable. Compared with easypoi, the reading and writing performance is slightly slow!
3. easypoi api is very rich, easyexcel function support, relatively simple.
In terms of the actual use of Xiaobian, easypoi has many advantages compared with easyexcel, especially its rich api. However, in the actual use process, it is found that when importing thousands of data, it is sometimes prone to exceptions, especially when the boss uses it, such an exception pops up suddenly, which can not be tolerated at this time.
However, this problem will not occur when using easyexcel. Therefore, if you often need to import a large amount of data, I recommend you use easyexcel.

Today, we will take the easyexcel framework as an example, combined with the actual development cases, to give you a detailed introduction to the use of easyexcel, and then in the next article, we will introduce easypoi. There may be some incomprehensible places. Netizens are welcome to criticize and point out!
Example: pandas is a NumPy based tool created to solve data analysis tasks.

2, Code case

2.1 adding dependent packages

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

2.2 export excel

The code is as follows (example):
There are two ways to export easyexcel: one is to generate files through entity class annotation, and the other is to generate files through dynamic parameterization.

2.2.1. Documents generated by entity class annotation

public class UserEntity {

    @ExcelProperty(value = "full name")
    private String name;

    @ExcelProperty(value = "Age")
    private int age;

    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    @ExcelProperty(value = "Operation time")
    private Date time;
 
 //set,get...
}
public static void main(String[] args) throws FileNotFoundException {
    List<UserEntity> dataList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName("Zhang San" + i);
        userEntity.setAge(20 + i);
        userEntity.setTime(new Date(System.currentTimeMillis() + i));
        dataList.add(userEntity);
    }
 //Define file output location
    FileOutputStream outputStream = new FileOutputStream(new File("/Users/panzhi/Documents/easyexcel-export-user1.xlsx"));
    EasyExcel.write(outputStream, UserEntity.class).sheet("User information").doWrite(dataList);
}

Run the program and open the file content results!

2.2.2 dynamic parameterization generation file

Dynamic parameterization generates files. This method is often used in small series. Based on it, we can encapsulate a public export tool class, which will be introduced separately later. The example code is as follows:

public static void main(String[] args) throws FileNotFoundException {
    //Define header
    List<List<String>> headList = new ArrayList<>();
    headList.add(Lists.newArrayList("full name"));
    headList.add(Lists.newArrayList("Age"));
    headList.add(Lists.newArrayList("Operation time"));

    //Define data body
    List<List<Object>> dataList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        List<Object> data = new ArrayList<>();
        data.add("Zhang San" + i);
        data.add(20 + i);
        data.add(new Date(System.currentTimeMillis() + i));
        dataList.add(data);
    }
    //Define file output location
    FileOutputStream outputStream = new FileOutputStream(new File("/Users/panzhi/Documents/easyexcel-export-user2.xlsx"));
    EasyExcel.write(outputStream).head(headList).sheet("User information").doWrite(dataList);
}

Run the program, open the file content, and the result is consistent with the above!

2.2.3. Generation of complex header

Many times, the header of the file we need to export is complex. For example, how should we export such a complex header as the following figure?

If you generate files by adding annotations to entity classes, you can do so in the following ways:

public class UserEntity {

    @ExcelProperty(value = "class")
    private String className;

    @ExcelProperty({"Student information", "full name"})
    private String name;

    @ExcelProperty({"Student information", "Age"})
    private int age;

    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    @ExcelProperty({"Student information", "Admission time"})
    private Date time;
 
 //set,get...
}

The expression {"student information" and "name"} indicates that multiple rows of data are inserted in the current column. The first row is the name of student information, and the second row is the name. Therefore, a multi-level header is formed!
If you use dynamic parameterization to generate files, the operation is also similar. The example code is as follows:

public static void main(String[] args) throws FileNotFoundException {
    //Define multi-level header
    List<List<String>> headList = new ArrayList<>();
    headList.add(Lists.newArrayList("class"));
    headList.add(Lists.newArrayList("Student information", "full name"));
    headList.add(Lists.newArrayList("Student information","Age"));
    headList.add(Lists.newArrayList("Student information","Admission time"));

    //Define data body
    List<List<Object>> dataList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        List<Object> data = new ArrayList<>();
        data.add("first grade~1 class");
        data.add("Zhang San" + i);
        data.add(20 + i);
        data.add(new Date(System.currentTimeMillis() + i));
        dataList.add(data);
    }
    //Define file output location
    FileOutputStream outputStream = new FileOutputStream(new File("/Users/panzhi/Documents/easyexcel-export-user3.xlsx"));
    EasyExcel.write(outputStream).head(headList).sheet("User information").doWrite(dataList);
}

Where lists Newarraylist ("student information", "name") means the same as above. Insert multiple rows under the current column, similar to:

List<String> list = new ArrayList<>();
list.add("Student information");
list.add("full name");

Lists.newArrayList programming comes from the guava toolkit

2.2.4. Custom style

In the actual use process, we may also need to customize the style for the file. For example, if you want to set the header to red, the content to green, and increase the column width and row width, how should you achieve it?

The operation is also very simple. Write a custom style class and inject it when writing.

/**
 * custom style
 * @return
 */
private static HorizontalCellStyleStrategy customerStyle(){
    // Header strategy
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    // The background is set to red
    headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short)20);
    headWriteCellStyle.setWriteFont(headWriteFont);
    // Content strategy
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    // Here, you need to specify FillPatternType as FillPatternType SOLID_ Foreground otherwise the background color cannot be displayed The header defaults to fillpattertype, so it can not be specified
    contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
    // Background green
    contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
    WriteFont contentWriteFont = new WriteFont();
    // font size
    contentWriteFont.setFontHeightInPoints((short)20);
    contentWriteCellStyle.setWriteFont(contentWriteFont);
    // This strategy is that the header is the style of the header, and the content is the style of the content. Other strategies can be implemented by themselves
    HorizontalCellStyleStrategy horizontalCellStyleStrategy =
            new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    return horizontalCellStyleStrategy;
}

When writing, inject it, such as the following dynamic export:

//Inject the custom style class through the registerWriteHandler method
EasyExcel.write(outputStream).registerWriteHandler(customerStyle()).head(headList).sheet("User information").doWrite(dataList);

2.3. Import excel

The import of easyexcel also supports two methods. As above, one is to read the file through entity class annotation, and the other is to read the file through dynamic listener.

2.3.1. Read the file by entity class annotation

When reading a file with entity class annotation, the excel header to be read needs to correspond to the entity class one by one. Take the following excel file as an example!

Read through annotation. You can specify the following table of columns or map through column names, but you can only choose one of them.

/**
 * Read entity class
 */
public class UserReadEntity {

    @ExcelProperty(value = "full name")
    private String name;

    /**
     * The third one is forced to read. It is not recommended to use index and name at the same time. Either an object only uses index or an object only uses name to match
     */
    @ExcelProperty(index = 1)
    private int age;

    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    @ExcelProperty(value = "Operation time")
    private Date time;

    //set,get...
}
public static void main(String[] args) throws FileNotFoundException {
 //Read file contents synchronously
    FileInputStream inputStream = new FileInputStream(new File("/Users/panzhi/Documents/easyexcel-user1.xls"));
    List<UserReadEntity> list = EasyExcel.read(inputStream).head(UserReadEntity.class).sheet().doReadSync();
    System.out.println(JSONArray.toJSONString(list));
}

Run the program and the output results are as follows:

[{"age":20,"name":"Zhang San 0","time":1616920360000},{"age":21,"name":"Zhang san1","time":1616920360000},{"age":22,"name":"Zhang San 2","time":1616920360000},{"age":23,"name":"Zhang SAN3","time":1616920360000},{"age":24,"name":"Zhang San 4","time":1616920360000},{"age":25,"name":"Zhang San 5","time":1616920360000},{"age":26,"name":"Zhang san6","time":1616920360000},{"age":27,"name":"Zhang san7","time":1616920360000},{"age":28,"name":"Zhang San 8","time":1616920360000},{"age":29,"name":"Zhang san9","time":1616920360000}]

2.3.2 dynamic listener reads files

There is an obvious difference between the dynamic listener and the above method in reading files. We need to rewrite an implementation class to listen to the data parsed by easyexcel line by line, and then encapsulate the data. Based on this, we can write a set of dynamic import tool classes. The detailed tool classes will be introduced below, and the example code is as follows:

/**
 * Create a listener that inherits from AnalysisEventListener
 */
public class UserDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDataListener.class);

    /**
     * Header data
     */
    private List<Map<Integer, String>> headList = new ArrayList<>();

    /**
     * Data body
     */
    private List<Map<Integer, String>> dataList = new ArrayList<>();

    /**
     * There will be return headers line by line
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        LOGGER.info("Parse to a header:{}", JSON.toJSONString(headMap));
        headList.add(headMap);
    }

    /**
     * This is called by every data parsing
     *
     * @param data
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        LOGGER.info("Parse to a piece of data:{}", JSON.toJSONString(data));
        dataList.add(data);
    }

    /**
     * When all data parsing is completed, it will be called
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        LOGGER.info("All data analysis completed!");
    }

    public List<Map<Integer, String>> getHeadList() {
        return headList;
    }

    public List<Map<Integer, String>> getDataList() {
        return dataList;
    }
}
public static void main(String[] args) throws FileNotFoundException {
    FileInputStream inputStream = new FileInputStream(new File("/Users/panzhi/Documents/easyexcel-user1.xls"));
    //Initialize a listener
    UserDataListener userDataListener = new UserDataListener();
    //Read file data
    EasyExcel.read(inputStream, userDataListener).sheet().doRead();
    System.out.println("Header:" + JSONArray.toJSONString(userDataListener.getHeadList()));
    System.out.println("Data body:" + JSONArray.toJSONString(userDataListener.getDataList()));
}

Run the program and the output results are as follows:

Header:[{0:"full name",1:"Age",2:"Operation time"}]
Data body:[{0:"Zhang San 0",1:"20",2:"2021-03-28 16:32:40"},{0:"Zhang san1",1:"21",2:"2021-03-28 16:32:40"},{0:"Zhang San 2",1:"22",2:"2021-03-28 16:32:40"},{0:"Zhang SAN3",1:"23",2:"2021-03-28 16:32:40"},{0:"Zhang San 4",1:"24",2:"2021-03-28 16:32:40"},{0:"Zhang San 5",1:"25",2:"2021-03-28 16:32:40"},{0:"Zhang san6",1:"26",2:"2021-03-28 16:32:40"},{0:"Zhang san7",1:"27",2:"2021-03-28 16:32:40"},{0:"Zhang San 8",1:"28",2:"2021-03-28 16:32:40"},{0:"Zhang san9",1:"29",2:"2021-03-28 16:32:40"}]

Where key indicates the following table!

2.3.3 complex header reading

In the actual development, we will also encounter the data reading of complex header. Take the following header as an example, how should we read it?

For example, we can also use the annotation method in the above file to read the file. If you use the annotation method in our file, you can also use the following method!

public class UserEntity {

    @ExcelProperty(value = "class")
    private String className;

    @ExcelProperty({"Student information", "full name"})
    private String name;

    @ExcelProperty({"Student information", "Age"})
    private int age;

    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    @ExcelProperty({"Student information", "Admission time"})
    private Date time;
 
 //set,get
}

//Read file

List<UserEntity> list = EasyExcel.read(filePath).head(UserEntity.class).sheet().doReadSync();
System.out.println(JSONArray.toJSONString(list));

The reading results are as follows:

[{"age":20,"className":"first grade~1 class","name":"Zhang San 0","time":1618719961000},{"age":21,"className":"first grade~1 class","name":"Zhang san1","time":1618719961000},{"age":22,"className":"first grade~1 class","name":"Zhang San 2","time":1618719961000},{"age":23,"className":"first grade~1 class","name":"Zhang SAN3","time":1618719961000},{"age":24,"className":"first grade~1 class","name":"Zhang San 4","time":1618719961000},{"age":25,"className":"first grade~1 class","name":"Zhang San 5","time":1618719961000},{"age":26,"className":"first grade~1 class","name":"Zhang san6","time":1618719961000},{"age":27,"className":"first grade~1 class","name":"Zhang san7","time":1618719961000},{"age":28,"className":"first grade~1 class","name":"Zhang San 8","time":1618719961000},{"age":29,"className":"first grade~1 class","name":"Zhang san9","time":1618719961000}]

If you use dynamic parameterization to generate files, you can use the dynamic listener to read the files. When reading, you need to specify the data line. The example code is as follows:

public static void main(String[] args) throws FileNotFoundException {
    FileInputStream inputStream = new FileInputStream(new File("/Users/panzhi/Documents/easyexcel-export-user4.xlsx"));
    //Initialize a listener
    UserDataListener userDataListener = new UserDataListener();
    //Read the file data, specify the row where the data is located, and use the headRowNumber method
    EasyExcel.read(inputStream, userDataListener).sheet().headRowNumber(2).doRead();
    System.out.println("Header:" + JSONArray.toJSONString(userDataListener.getHeadList()));
    System.out.println("Data body:" + JSONArray.toJSONString(userDataListener.getDataList()));
}

The reading results are as follows:

Header:[{0:"class",1:"Student information",2:"Student information",3:"Student information"},{0:"class",1:"full name",2:"Age",3:"Admission time"}]
Data body:[{0:"first grade~1 class",1:"Zhang San 0",2:"20",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang san1",2:"21",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang San 2",2:"22",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang SAN3",2:"23",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang San 4",2:"24",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang San 5",2:"25",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang san6",2:"26",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang san7",2:"27",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang San 8",2:"28",3:"2021-04-18 12:26:01"},{0:"first grade~1 class",1:"Zhang san9",2:"29",3:"2021-04-18 12:26:01"}]

3, Dynamic export and import tool class encapsulation

In actual use and development, it is impossible to write a method for every excel import and export requirement, and many business requirements are imported and exported dynamically. There is no way to read or write files based on entity class annotation
Therefore, based on the dynamic parameterized file generation method and the dynamic listener file reading method, we can package a set of dynamic export tool classes separately, which saves us a lot of repeated work every time. The following is the tool classes encapsulated by me in the actual use process, which I share with you here!
Dynamic export tool class

public class DynamicEasyExcelExportUtils {

    private static final Logger log = LoggerFactory.getLogger(DynamicEasyExcelExportUtils.class);

    private static final String DEFAULT_SHEET_NAME = "sheet1";

    /**
     * Dynamically generate export template (single header)
     * @param headColumns Column name
     * @return            excel File stream
     */
    public static byte[] exportTemplateExcelFile(List<String> headColumns){
        List<List<String>> excelHead = Lists.newArrayList();
        headColumns.forEach(columnName -> { excelHead.add(Lists.newArrayList(columnName)); });
        byte[] stream = createExcelFile(excelHead, new ArrayList<>());
        return stream;
    }

    /**
     * Dynamically generate template (complex header)
     * @param excelHead   Column name
     * @return
     */
    public static byte[] exportTemplateExcelFileCustomHead(List<List<String>> excelHead){
        byte[] stream = createExcelFile(excelHead, new ArrayList<>());
        return stream;
    }

    /**
     * Dynamic export file
     * @param headColumnMap  Sequential header
     * @param dataList       Data body
     * @return
     */
    public static byte[] exportExcelFile(LinkedHashMap<String, String> headColumnMap, List<Map<String, Object>> dataList){
        //Get column name
        List<List<String>> excelHead = new ArrayList<>();
        if(MapUtils.isNotEmpty(headColumnMap)){
            //key is the matching character and value is the column name. If multi-level column names are separated by commas
            headColumnMap.entrySet().forEach(entry -> {
                excelHead.add(Lists.newArrayList(entry.getValue().split(",")));
            });
        }
        List<List<Object>> excelRows = new ArrayList<>();
        if(MapUtils.isNotEmpty(headColumnMap) && CollectionUtils.isNotEmpty(dataList)){
            for (Map<String, Object> dataMap : dataList) {
                List<Object> rows = new ArrayList<>();
                headColumnMap.entrySet().forEach(headColumnEntry -> {
                    if(dataMap.containsKey(headColumnEntry.getKey())){
                        Object data = dataMap.get(headColumnEntry.getKey());
                        rows.add(data);
                    }
                });
                excelRows.add(rows);
            }
        }
        byte[] stream = createExcelFile(excelHead, excelRows);
        return stream;
    }

    /**
     * Generate file
     * @param excelHead
     * @param excelRows
     * @return
     */
    private static byte[] createExcelFile(List<List<String>> excelHead, List<List<Object>> excelRows){
        try {
            if(CollectionUtils.isNotEmpty(excelHead)){
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                EasyExcel.write(outputStream).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .head(excelHead)
                        .sheet(DEFAULT_SHEET_NAME)
                        .doWrite(excelRows);
                return outputStream.toByteArray();
            }
        } catch (Exception e) {
            log.error("Dynamic generation excel File failed, headColumns: " + JSONArray.toJSONString(excelHead) + ",excelRows: " + JSONArray.toJSONString(excelRows), e);
        }
        return null;
    }

    /**
     * Export file test
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //Export files containing data content
        LinkedHashMap<String, String> headColumnMap = Maps.newLinkedHashMap();
        headColumnMap.put("className","class");
        headColumnMap.put("name","Student information,full name");
        headColumnMap.put("sex","Student information,Gender");
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("className", "first grade");
            dataMap.put("name", "Zhang San" + i);
            dataMap.put("sex", "male");
            dataList.add(dataMap);
        }
        byte[] stream = exportExcelFile(headColumnMap, dataList);
        FileOutputStream outputStream = new FileOutputStream(new File("/Users/panzhi/Documents/easyexcel-export-user5.xlsx"));
        outputStream.write(stream);
        outputStream.close();
    }
}

Dynamic import tool class

/**
 * Create a listener
 */
public class DynamicEasyExcelListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDataListener.class);

    /**
     * Header data (store all header data)
     */
    private List<Map<Integer, String>> headList = new ArrayList<>();

    /**
     * Data body
     */
    private List<Map<Integer, String>> dataList = new ArrayList<>();

    /**
     * There will be return headers line by line
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        LOGGER.info("Parse to a header:{}", JSON.toJSONString(headMap));
        //Store all header data
        headList.add(headMap);
    }

    /**
     * This is called by every data parsing
     *
     * @param data
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        LOGGER.info("Parse to a piece of data:{}", JSON.toJSONString(data));
        dataList.add(data);
    }

    /**
     * When all data parsing is completed, it will be called
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // Data should also be saved here to ensure that the last remaining data is also stored in the database
        LOGGER.info("All data analysis completed!");
    }

    public List<Map<Integer, String>> getHeadList() {
        return headList;
    }

    public List<Map<Integer, String>> getDataList() {
        return dataList;
    }
}
/**
 * Write import tool class
 */
public class DynamicEasyExcelImportUtils {

    /**
     * Get all columns and data bodies dynamically, and parse the data from the first row by default
     * @param stream
     * @return
     */
    public static List<Map<String,String>> parseExcelToView(byte[] stream) {
        return parseExcelToView(stream, 1);
    }

    /**
     * Get all columns and data bodies dynamically
     * @param stream           excel File stream
     * @param parseRowNumber   Specify read row
     * @return
     */
    public static List<Map<String,String>> parseExcelToView(byte[] stream, Integer parseRowNumber) {
        DynamicEasyExcelListener readListener = new DynamicEasyExcelListener();
        EasyExcelFactory.read(new ByteArrayInputStream(stream)).registerReadListener(readListener).headRowNumber(parseRowNumber).sheet(0).doRead();
        List<Map<Integer, String>> headList = readListener.getHeadList();
        if(CollectionUtils.isEmpty(headList)){
            throw new RuntimeException("Excel Header not included");
        }
        List<Map<Integer, String>> dataList = readListener.getDataList();
        if(CollectionUtils.isEmpty(dataList)){
            throw new RuntimeException("Excel No data included");
        }
        //Get the header and get the last parsed column header data
        Map<Integer, String> excelHeadIdxNameMap = headList.get(headList.size() -1);
        //Encapsulate data body
        List<Map<String,String>> excelDataList = Lists.newArrayList();
        for (Map<Integer, String> dataRow : dataList) {
            Map<String,String> rowData = new LinkedHashMap<>();
            excelHeadIdxNameMap.entrySet().forEach(columnHead -> {
                rowData.put(columnHead.getValue(), dataRow.get(columnHead.getKey()));

            });
            excelDataList.add(rowData);
        }
        return excelDataList;
    }

    /**
     * File import test
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream(new File("/Users/panzhi/Documents/easyexcel-export-user5.xlsx"));
        byte[] stream = IoUtils.toByteArray(inputStream);
        List<Map<String,String>> dataList = parseExcelToView(stream, 2);
        System.out.println(JSONArray.toJSONString(dataList));
        inputStream.close();
    }

}

In order to facilitate the subsequent operation process, when parsing data, the column name will be used as the key!

4, Summary

Taking the actual use scenario as an example, this paper briefly introduces the use of easyexcel, especially dynamic export. Based on the needs of business, this paper makes a public tool class to facilitate the subsequent rapid development and avoid repeated labor!
Of course, the functions of easyexcel are not only those described above, but also the filling of excel based on template and the export of restful on the web. The use methods are roughly the same. I hope this article will be helpful to you!

Keywords: Java poi elementUI

Added by VinnyWolf on Fri, 04 Mar 2022 03:31:17 +0200