Java operates Excel, it is enough to read this article carefully [key]

1.1 Overview

In our usual development, there are often Excelfunctions for importing and exporting operations. Let's summarize this article.

Here are some common methods recommended for you:Apache POI、EasyPOI、Alibaba Easy Excel

1.2 Apache POI

About a long time ago, Microsoft’s spreadsheet software Excelwas operate, intuitive and convenient to store data, and also supported printing reports. At the beginning of its birth, it was favored by white-collar workers in the office and greatly improved work efficiency. Soon after , has become an essential tool in the office.

With the rise of more new languages, such as the ones we are familiar with java, some teams began to develop a set of Exceloperating tools that can seamlessly switch with the software!

Of course, in javathe ecosystem, Excelthere are still many third-party tools that can be seamlessly connected. At the beginning, I will list three for you, because they are Apache poithe most widely used in the industry, so other tools will not be introduced too much!

1.2.1 Environment preparation

<dependencies>
    <!--xls(03)-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
    <!--xlsx(07)-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
    <!--时间格式化工具-->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.6</version>
    </dependency>
</dependencies>

1.2.2 Exportexcel

The export operation is to use to Javawrite data Excelto . The common scenario is to export the data on the page. These data may be financial data or commodity data, and return to the user to download the file Excelafter .

In poithe tool library, export apican be divided into three ways

  • HSSF method : The file format exported by this method is office 2003a special format, that is .xls, the advantage is that the export data is fast, but the most 65536rows of data
  • XSSF method : The file format exported by this method is office 2007a special format, that is .xlsx, the advantage is that the exported data is not limited by the number of rows, and the disadvantage is that the export speed is slow
  • SXSSF method : SXSSFis XSSF APIa compatible streaming extension, mainly to solve XSSFthe problem of memory overflow when using the method to export large amounts of data, and supports the export of large batches of exceldata

1.2.2.1 HSSFMode export ( .xlsmode)

HSSFmethod, only supports 65536data export at most, if the number exceeds this number, an error will be reported!

package cn.tedu.excel.test;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;

/**
 * HSSF方式导出:HSSF方式,最多只支持65536条数据导出,超过这个条数会报错!
 * 就是.xls模式
 */
public class ExcelWrite2003Test {
    
    
    private static  String PATH = "/Users/lixin/Desktop/";//自己输出的路径

    public static void main(String[] args) throws Exception {
    
    
        //时间
        long begin = System.currentTimeMillis();

        //创建一个工作簿
        Workbook workbook = new HSSFWorkbook();
        //创建表
        Sheet sheet = workbook.createSheet();
        //写入数据
        for (int rowNumber = 0; rowNumber < 65536; rowNumber++) {
    
    
            //创建行
            Row row = sheet.createRow(rowNumber);
            for (int cellNumber = 0; cellNumber < 10; cellNumber++) {
    
    
                //创建列
                Cell cell = row.createCell(cellNumber);
                cell.setCellValue(cellNumber);
            }
        }
        System.out.println("结束!");
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户信息表-XLS.xls");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println("时间为:"+(double) (end - begin) / 1000);//2.262s
    }
}

1.2.2.2 XSSFWay to export ( .xlsx)

XSSFThe method supports the export of large batches of data. All the data is first written into the memory and then exported, which is prone to memory overflow!

package cn.tedu.excel.test;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * .xlsx方式
 */
public class ExcelWrite2007Test {
    
    
    public static String PATH = "/Users/lixin/Desktop/";

    public static void main(String[] args) throws Exception {
    
    
        //时间
        long begin = System.currentTimeMillis();

        //创建一个工作簿
        Workbook workbook = new XSSFWorkbook();
        //创建表
        Sheet sheet = workbook.createSheet();
        //写入数据
        for (int rowNumber = 0; rowNumber < 65537; rowNumber++) {
    
    
            Row row = sheet.createRow(rowNumber);
            for (int cellNumber = 0; cellNumber < 10; cellNumber++) {
    
    
                Cell cell = row.createCell(cellNumber);
                cell.setCellValue(cellNumber);
            }
        }
        System.out.println("结束");

        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户信息表-XLSX.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end - begin) / 1000);//5.003s
    }
}

1.2.2.3 SXSSFWays to export

SXSSFThe method is XSSFan extension of the method. The main feature is low memory. When exporting, the data is first written to the disk and then exported, so as to avoid insufficient memory and cause the program to run abnormally. The disadvantage is that it runs very slowly!

package cn.tedu.excel.test;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.FileOutputStream;

public class ExcelWriteSXSSFTest {
    
    
    public static String PATH = "/Users/lixin/Desktop/";

    public static void main(String[] args) throws Exception {
    
    
        //时间
        long begin = System.currentTimeMillis();

        //创建一个工作簿
        Workbook workbook = new SXSSFWorkbook();

        //创建表
        Sheet sheet = workbook.createSheet();

        //写入数据
        for (int rowNumber = 0; rowNumber < 100000; rowNumber++) {
    
    
            Row row = sheet.createRow(rowNumber);
            for (int cellNumber = 0; cellNumber < 10; cellNumber++) {
    
    
                Cell cell = row.createCell(cellNumber);
                cell.setCellValue(cellNumber);
            }
        }
        System.out.println("over");

        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户信息表-SXSSF.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end - begin) / 1000);//6.39s
    }
}

1.2.3 Importexcel

The import operation is to use the tool library to parse excelthe data in the data , and then write the data into the database!javaexcel

Similarly, in poithe tool library, apithere are three ways to import, corresponding to the above export one by one!

1.2.3.1 HSSFMethod import

package cn.tedu.excel.test;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.joda.time.DateTime;

import java.io.FileInputStream;
import java.util.Date;

public class ExcelRead2003Test {
    
    
    public static String PATH = "/Users/lixin/Desktop/";

    public static void main(String[] args) throws Exception {
    
    
        //获取文件流
        FileInputStream inputStream = new FileInputStream(PATH + "用户信息表2003read.xls");

        //1.创建工作簿,使用excel能操作的这边都看看操作
        Workbook workbook = new HSSFWorkbook(inputStream);
        //2.得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3.得到行
        Row row = sheet.getRow(0);
        //4.得到列
        Cell cell = row.getCell(0);
        getValue(cell);
        inputStream.close();
    }

    public static void getValue(Cell cell){
    
    
        //匹配类型数据
        if (cell != null) {
    
    
            CellType cellType = cell.getCellType();
            String cellValue = "";
            switch (cellType) {
    
    
                case STRING: //字符串
                    System.out.print("[String类型]");
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN: //布尔类型
                    System.out.print("[boolean类型]");
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case BLANK: //空
                    System.out.print("[BLANK类型]");
                    break;
                case NUMERIC: //数字(日期、普通数字)
                    System.out.print("[NUMERIC类型]");
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
    
     //日期
                        System.out.print("[日期]");
                        Date date = cell.getDateCellValue();
                        cellValue = new DateTime(date).toString("yyyy-MM-dd");
                    } else {
    
    
                        //不是日期格式,防止数字过长
                        System.out.print("[转换为字符串输出]");
                        cell.setCellType(CellType.STRING);
                        cellValue = cell.toString();
                    }
                    break;
                case ERROR:
                    System.out.print("[数据类型错误]");
                    break;
            }
            System.out.println(cellValue);
        }
    }
}

The output result is similar to that shown in the figure:
insert image description here

1.2.3.2 XSSFMethod import

package cn.tedu.excel.test;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;

import java.io.FileInputStream;
import java.util.Date;

public class ExcelRead2007Test {
    
    
    public static String PATH = "/Users/lixin/Desktop/";

    public static void main(String[] args) throws Exception {
    
    
        //获取文件流
        FileInputStream inputStream = new FileInputStream(PATH + "用户信息表2007read.xlsx");

        //1.创建工作簿,使用excel能操作的这边都看看操作
        Workbook workbook = new XSSFWorkbook(inputStream);
        //2.得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3.得到行
        Row row = sheet.getRow(0);
        //4.得到列
        Cell cell = row.getCell(0);
        getValue(cell);
        inputStream.close();
    }
    public static void getValue(Cell cell){
    
    
        //匹配类型数据
        if (cell != null) {
    
    
            CellType cellType = cell.getCellType();
            String cellValue = "";
            switch (cellType) {
    
    
                case STRING: //字符串
                    System.out.print("[String类型]");
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN: //布尔类型
                    System.out.print("[boolean类型]");
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case BLANK: //空
                    System.out.print("[BLANK类型]");
                    break;
                case NUMERIC: //数字(日期、普通数字)
                    System.out.print("[NUMERIC类型]");
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
    
     //日期
                        System.out.print("[日期]");
                        Date date = cell.getDateCellValue();
                        cellValue = new DateTime(date).toString("yyyy-MM-dd");
                    } else {
    
    
                        //不是日期格式,防止数字过长
                        System.out.print("[转换为字符串输出]");
                        cell.setCellType(CellType.STRING);
                        cellValue = cell.toString();
                    }
                    break;
                case ERROR:
                    System.out.print("[数据类型错误]");
                    break;
            }
            System.out.println(cellValue);
        }
    }
}

1.2.3.3 SXSSFMethod import

package cn.tedu.excel.test;

import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class ExcelReadSXSSFTest {
    
    
    public static String PATH = "/Users/lixin/Desktop/";

    public static void main(String[] args) throws Exception {
    
    
        //获取文件流

        //1.创建工作簿,使用excel能操作的这边都看看操作
        OPCPackage opcPackage = OPCPackage.open(PATH + "用户信息表2007read.xlsx");
        XSSFReader xssfReader = new XSSFReader(opcPackage);
        StylesTable stylesTable = xssfReader.getStylesTable();
        ReadOnlySharedStringsTable sharedStringsTable = new ReadOnlySharedStringsTable(opcPackage);
        // 创建XMLReader,设置ContentHandler
        XMLReader xmlReader = SAXHelper.newXMLReader();
        xmlReader.setContentHandler(new XSSFSheetXMLHandler(stylesTable, sharedStringsTable, new SimpleSheetContentsHandler(), false));
        // 解析每个Sheet数据
        Iterator<InputStream> sheetsData = xssfReader.getSheetsData();
        while (sheetsData.hasNext()) {
    
    
            try (InputStream inputStream = sheetsData.next();) {
    
    
                xmlReader.parse(new InputSource(inputStream));
            }
        }
    }
    /**
     * 内容处理器
     */
    public static class SimpleSheetContentsHandler implements XSSFSheetXMLHandler.SheetContentsHandler {
    
    

        protected List<String> row;

        @Override
        public void startRow(int rowNum) {
    
    
            row = new ArrayList<>();
        }

        @Override
        public void endRow(int rowNum) {
    
    
            if (row.isEmpty()) {
    
    
                return;
            }
            // 处理数据
            System.out.println(row.stream().collect(Collectors.joining("   ")));
        }

        @Override
        public void cell(String cellReference, String formattedValue, XSSFComment comment) {
    
    
            row.add(formattedValue);
        }

        @Override
        public void headerFooter(String text, boolean isHeader, String tagName) {
    
    
        }
    }
}

insert image description here

1.3 Easypoi

In the past, there was a big guy programmer who chatted with business people after jumping to a company. These salesmen excelhave many requirements for reports. For example, if they want a report, his table header is a multi-line Header, after a few days, he wants to add styles to these headers, such as marking key data in red, and in a few days, he wants to add a piece of total data at the end, and so on!

It was okay at first, it was all copy, copy, and later found that there were a lot of repeated codes in the system, so one day I really couldn't stand it, and used annotations to get these customizations into high-level logic, and pulled out the public, so it was born easypoi! Its bottom layer is also based apache poion in-depth development. Its main feature is to simplify more repetitive work and avoid writing repetitive code!

Next, let's take a look at this tall open source tool:easypoi

1.3.1 Environment preparation

<dependencies>
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-base</artifactId>
        <version>4.1.0</version>
    </dependency>
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-web</artifactId>
        <version>4.1.0</version>
    </dependency>
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-annotation</artifactId>
        <version>4.1.0</version>
    </dependency>
	<dependency>
	    <groupId>com.googlecode.json-simple</groupId>
	    <artifactId>json-simple</artifactId>
	    <version>1.1.1</version>
	</dependency>
</dependencies>

1.3.2 Using annotations to export and import

easypoiThe biggest highlight is the export and import based on the annotation entity class excel, which is very easy to use!

We create an entity class UserEntity, where @Excelthe annotation represents the header information of the exported file.

Add Lombokplugins, overrides setand getmethods

1.3.2.1 Export operation

package cn.tedu.excel.easypoi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
    
    
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private int age;
    @Excel(name = "操作时间",format="yyyy-MM-dd HH:mm:ss", width = 20.0)
    private Date time;

    public static void main(String[] args) throws Exception {
    
    
        List<UserEntity> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
    
    
            UserEntity userEntity = new UserEntity();
            userEntity.setName("张三" + i);
            userEntity.setAge(20 + i);
            userEntity.setTime(new Date(System.currentTimeMillis() + i));
            dataList.add(userEntity);
        }
        //生成excel文档
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户","用户信息"),
                UserEntity.class, dataList);
        FileOutputStream fos = new FileOutputStream("/Users/lixin/Desktop/easypoi-user.xls");
        workbook.write(fos);
        fos.close();
    }
}

The export file preview is as follows:
insert image description here

1.3.2.2 Import operation

package cn.tedu.excel.easypoi;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.util.Date;
import java.util.List;
import org.json.simple.JSONArray;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentEntity {
    
    
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private int age;
    @Excel(name = "操作时间",format="yyyy-MM-dd HH:mm:ss", width = 20.0)
    private Date time;

    public static void main(String[] args) {
    
    
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        long start = new Date().getTime();
        List<StudentEntity> list = ExcelImportUtil.importExcel(new File("/Users/lixin/Desktop/easypoi-user1.xls"),
                UserEntity.class, params);
        System.out.println(new Date().getTime() - start);
        System.out.println(JSONArray.toJSONString(list));
    }
}

The output is:

[UserEntity(name=张三0, age=20, time=Mon Mar 29 11:29:52 CST 2021),UserEntity(name=李四, age=21, time=Mon Mar 29 11:29:52 CST 2021),UserEntity(name=王武, age=22, time=Mon Mar 29 11:29:52 CST 2021),UserEntity(name=赵六, age=23, time=Mon Mar 29 11:29:52 CST 2021),UserEntity(name=null, age=0, time=null),UserEntity(name=null, age=0, time=null),UserEntity(name=null, age=0, time=null),UserEntity(name=null, age=0, time=null),UserEntity(name=null, age=0, time=null),UserEntity(name=null, age=0, time=null)]

1.3.3 Custom data structure export and import

easypoiIt also supports custom data structure export and import excel.

Custom data exportexcel

1.3.3.1 Export operation

public static void main(String[] args) throws Exception {
    
    
    //封装表头
    List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
    entityList.add(new ExcelExportEntity("姓名", "name"));
    entityList.add(new ExcelExportEntity("年龄", "age"));
    ExcelExportEntity entityTime = new ExcelExportEntity("操作时间", "time");
    entityTime.setFormat("yyyy-MM-dd HH:mm:ss");
    entityTime.setWidth(20.0);
    entityList.add(entityTime);
    //封装数据体
    List<Map<String, Object>> dataList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
    
    
        Map<String, Object> userEntityMap = new HashMap<>();
        userEntityMap.put("name", "张三" + i);
        userEntityMap.put("age", 20 + i);
        userEntityMap.put("time", new Date(System.currentTimeMillis() + i));
        dataList.add(userEntityMap);
    }
    //生成excel文档
    Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生","用户信息"), entityList, dataList);
    FileOutputStream fos = new FileOutputStream("/Users/lixin/Desktop/easypoi-user2.xls");
    workbook.write(fos);
    fos.close();
}

1.3.3.2 Import operation

public static void main(String[] args) {
    
    
    ImportParams params = new ImportParams();
    params.setTitleRows(1);
    params.setHeadRows(1);
    long start = new Date().getTime();
    List<Map<String, Object>> list = ExcelImportUtil.importExcel(new File("/Users/lixin/Desktop/easypoi-user2.xls"),
            Map.class, params);
    System.out.println(new Date().getTime() - start);
    System.out.println(JSONArray.toJSONString(list));
}

For more apioperations , please visit Easypo - ithe interface documentation

1.4 Easyexcel

easyexcelexcelIt is an analysis tool open sourced by Alibaba , and the underlying logic is also based on apache poisecondary development. The difference is that when reading and writing data, saxthe mode to parse line by line, and it can still run stably even when the amount of concurrency is large!

Below, let's take a look at this new star!

1.4.1 Environment preparation

<!-- EasyExcel -->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>2.2.6</version>
 </dependency>
 <!--常用工具库-->
 <dependency>
     <groupId>com.google.guava</groupId>
     <artifactId>guava</artifactId>
     <version>29.0-jre</version>
 </dependency>

1.4.2 Using annotations to export and import

easyexcelIt also supports exporting and importing using annotations!

First, we create an entity class UserEntity, where @ExcelPropertythe annotation represents the header information of the exported file.

1.4.2.1 Export operation

package cn.tedu.excel.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
    
    
    @ExcelProperty(value = "姓名")
    private String name;

    @ExcelProperty(value = "年龄")
    private int age;

    @DateTimeFormat(fallbackPatterns = "yyyy-MM-dd HH:mm:ss")
    @ExcelProperty(value = "操作时间")
    private Date time;

    public static void main(String[] args) {
    
    
        List<UserEntity> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
    
    
            UserEntity userEntity = new UserEntity();
            userEntity.setName("张三" + i);
            userEntity.setAge(20 + i);
            userEntity.setTime(new Date(System.currentTimeMillis() + i));
            dataList.add(userEntity);
        }
        EasyExcel.write("/Users/lixin/Desktop/easyexcel-user1.xls", UserEntity.class).sheet("用户信息").doWrite(dataList);
    }
}

Export preview image:

insert image description here

1.4.2.2 Import operation

package cn.tedu.excel.easyexcel;

import com.alibaba.excel.EasyExcel;
import org.json.simple.JSONArray;

import java.util.List;

public class DemoData {
    
    
    public static void main(String[] args) {
    
    
        String filePath = "/Users/lixin/Desktop/easyexcel-user1.xls";
        List<DemoData> list = EasyExcel.read(filePath).head(UserEntity.class).sheet().doReadSync();
        System.out.println(JSONArray.toJSONString(list));
    }
}

The results show that:

[UserEntity(name=张三0, age=20, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三1, age=21, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三2, age=22, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三3, age=23, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三4, age=24, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三5, age=25, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三6, age=26, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三7, age=27, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三8, age=28, time=Mon Mar 29 16:42:20 CST 2021),UserEntity(name=张三9, age=29, time=Mon Mar 29 16:42:20 CST 2021)]

1.4.3 Custom data structure export and import

easyexcelIt also supports custom data structure export and import excel.

1.4.3.1 Export operation

public static void main(String[] args) {
    
    
    //表头
    List<List<String>> headList = new ArrayList<>();
    headList.add(Lists.newArrayList("姓名"));
    headList.add(Lists.newArrayList("年龄"));
    headList.add(Lists.newArrayList("操作时间"));

    //数据体
    List<List<Object>> dataList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
    
    
        List<Object> data = new ArrayList<>();
        data.add("张三" + i);
        data.add(20 + i);
        data.add(new Date(System.currentTimeMillis() + i));
        dataList.add(data);
    }
    EasyExcel.write("/Users/hello/Documents/easyexcel-user2.xls").head(headList).sheet("用户信息").doWrite(dataList);
}

1.4.3.2 Import operation

public static void main(String[] args) {
    
    
    String filePath = "/Users/panzhi/Documents/easyexcel-user2.xls";
    UserDataListener userDataListener = new UserDataListener();
    EasyExcel.read(filePath, userDataListener).sheet().doRead();
    System.out.println("表头:" + JSONArray.toJSONString(userDataListener.getHeadList()));
    System.out.println("数据体:" + JSONArray.toJSONString(userDataListener.getDataList()));
}

The running result is shown in the figure:

表头:[{
    
    0:"姓名",1:"年龄",2:"操作时间"}]
数据体:[{
    
    0:"张三0",1:"20",2:"2021-03-29 16:31:39"},{
    
    0:"张三1",1:"21",2:"2021-03-29 16:31:39"},{
    
    0:"张三2",1:"22",2:"2021-03-29 16:31:39"},{
    
    0:"张三3",1:"23",2:"2021-03-29 16:31:39"},{
    
    0:"张三4",1:"24",2:"2021-03-29 16:31:39"},{
    
    0:"张三5",1:"25",2:"2021-03-29 16:31:39"},{
    
    0:"张三6",1:"26",2:"2021-03-29 16:31:39"},{
    
    0:"张三7",1:"27",2:"2021-03-29 16:31:39"},{
    
    0:"张三8",1:"28",2:"2021-03-29 16:31:39"},{
    
    0:"张三9",1:"29",2:"2021-03-29 16:31:39"}]

More apioperations can be accessed easyexcel- interface documentation!

1.5 Summary

In general, Easypoiand Easyexcelare based Apache poion secondary development.

The differences are:
1. EasypoiWhen reading and writing data, the priority is to write the data into the memory first. The advantage is that the reading and writing performance is very high, but when the amount of data is large, it will appear oom. Of course, it also provides saxthe mode of reading The writing method needs to call a specific method implementation.
2. Reading and writing data Easyexcelbased on patterns will not cause problems. The program has verification of high concurrency scenarios, so the program runs relatively stable. Relatively speaking , the read and write performance is slightly slower!saxoomEasypoi

EasypoiEasyexcelAnother difference is Easypoithat the customized export support is very rich. If the current project needs, the amount of concurrency is not large, the amount of data is not large, but the file excelstyles to be exported vary widely, then I recommend you to use it easypoi; otherwise, use easyexcel!

Guess you like

Origin blog.csdn.net/weixin_42039228/article/details/123794466