Java操作excel的三种常见方法实例
作者:经理,天台风好大 发布时间:2022-12-11 02:29:55
目录
前言
一、Apache poi
1.1 首先添加依赖
1.2 导出excel
1.2.1 HSSF方式导出(.xls方式)
1.2.2 XSSF方式导出(.xlsx)
1.2.3、SXSSF方式导出
1.3 导入excel
1.3.1 HSSF方式导入
1.3.2 XSSF方式导入
1.3.3 SXSSF方式导入
二、Easypoi
2.1 添加依赖包
2.2 采用注解导出导入
2.2.1 导出操作
2.2.2 导入操作
2.3 自定义数据结构导出导入
2.3.1 导出操作
2.3.2 导入操作
三、Easyexcel
3.1 添加依赖包
3.2 采用注解导出导入
3.2.1 导出操作
3.3 自定义数据结构导出导入
3.3.1 导出操作
3.3.2 导入操作
四、总结
前言
在平时的业务系统开发中,少不了需要用到导出、导入excel功能,今天我们就一起来总结一下!
下面给大家介绍一下几种常用方法:
apache poi
easypoi
easyexcel
一、Apache poi
大概在很久很久以前,微软的电子表格软件 Excel 以操作简单、存储数据直观方便,还支持打印报表,在诞生之初,可谓深得办公室里的白领青睐,极大的提升了工作的效率,不久之后,便成了办公室里的必备工具。
随着更多的新语言的崛起,例如我们所熟悉的 java,后来便有一些团队开始开发一套能与 Excel 软件无缝切换的操作工具!
当然,在java生态体系里面,能与Excel无缝衔接的第三方工具还有很多,在开始也给大家列出来三个,因为 apache poi 在业界使用的最广泛,因此其他的工具不做过多介绍!
话不多说,直接开撸!
1.1 首先添加依赖
<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 导出excel
导出操作,即使用 Java 写出数据到 Excel 中,常见场景是将页面上的数据导出,这些数据可能是财务数据,也可能是商品数据,生成 Excel 后返回给用户下载文件。
在 poi 工具库中,导出 api 可以分三种方式
HSSF方式: 这种方式导出的文件格式为office 2003专用格式,即.xls,优点是导出数据速度快,但是 最多65536行 数据
XSSF方式: 这种方式导出的文件格式为office 2007专用格式,即.xlsx,优点是导出的数据不受行数限制,缺点导出速度慢
SXSSF方式: SXSSF 是 XSSF API的兼容流式扩展,主要解决当使用 XSSF 方式导出大数据量时,内存溢出的问题,支持导出大批量的excel数据
1.2.1 HSSF方式导出(.xls方式)
HSSF方式,最多只支持65536条数据导出,超过这个条数会报错!
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 XSSF方式导出(.xlsx)
XSSF方式支持大批量数据导出,所有的数据先写入内存再导出,容易出现内存溢出!
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.3、SXSSF方式导出
SXSSF方式是XSSF方式的一种延伸,主要特性是低内存,导出的时候,先将数据写入磁盘再导出,避免报内存不足,导致程序运行异常,缺点是运行很慢!
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.3 导入excel
导入操作,即将 excel 中的数据采用java工具库将其解析出来,进而将 excel 数据写入数据库!
同样,在 poi 工具库中,导入 api 也分三种方式,与上面的导出一一对应!
1.3.1 HSSF方式导入
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);
}
}
}
输出结果类似如图所示:
1.3.2 XSSF方式导入
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.3.3 SXSSF方式导入
package cn.tedu.excel.test;
import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.opc.O * ackage;
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能操作的这边都看看操作
O * ackage opcPackage = O * ackage.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) {
}
}
}
二、Easypoi
以前的以前,有个大佬程序员,跳到一家公司之后就和业务人员聊上了,这些业务员对excel报表有着许许多多的要求,比如想要一个报表,他的表头是一个多行表头,过几天之后,他想要给这些表头添加样式,比如关键的数据标红,再过几天,他想要再末尾添加一条合计的数据,等等!
起初还好,都是copy、copy,之后发现系统中出现大量的重复代码,于是有一天真的忍受不了了,采用注解搞定来搞定这些定制化成程度高的逻辑,将公共化抽离出来,于是诞生了 easypoi!它的底层也是基于 apache poi 进行深度开发的,它主要的特点就是将更多重复的工作,全部简单化,避免编写重复的代码!
下面,我们就一起来了解一下这款高大上的开源工具:easypoi
2.1 添加依赖包
<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>
2.2 采用注解导出导入
easypoi 最大的亮点就是基于注解实体类来导出、导入excel,使用起来非常简单!
我们创建一个实体类UserEntity,其中@Excel注解表示导出文件的头部信息。
添加Lombok插件,替代set和get方法
2.2.1 导出操作
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();
}
}
导出文件预览图如下:
2.2.2 导入操作
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));
}
}
输出结果为:
[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)]
2.3 自定义数据结构导出导入
easypoi 同样也支持自定义数据结构导出导入excel。
自定义数据导出 excel
2.3.1 导出操作
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();
}
2.3.2 导入操作
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));
}
更多的 api 操作可以访问 Easypoi - 接口文档
三、Easyexcel
easyexcel 是阿里巴巴开源的一款 excel 解析工具,底层逻辑也是基于 apache poi 进行二次开发的。不同的是,再读写数据的时候,采用 sax 模式一行一行解析,在并发量很大的情况下,依然能稳定运行!
下面,我们就一起来了解一下这款新起之秀!
3.1 添加依赖包
<!-- 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>
3.2 采用注解导出导入
easyexcel 同样也支持采用注解方式进行导出、导入!
首先,我们创建一个实体类UserEntity,其中@ExcelProperty注解表示导出文件的头部信息。
3.2.1 导出操作
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);
}
}
导出预览图:
3.2.2 导入操作
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));
}
}
结果显示:
[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)]
3.3 自定义数据结构导出导入
easyexcel 同样也支持自定义数据结构导出导入excel。
3.3.1 导出操作
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);
}
3.3.2 导入操作
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()));
}
运行结果如图所示:
表头:[{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"}]
更多的 api 操作可以访问 easyexcel - 接口文档!
四、总结
总体来说,Easypoi 和 Easyexcel 都是基于Apache poi进行二次开发的。
不同点在于:
Easypoi 在读写数据的时候,优先是先将数据写入内存,优点是读写性能非常高,但是当数据量很大的时候,会出现oom,当然它也提供了 sax 模式的读写方式,需要调用特定的方法实现。
Easyexcel 基于sax模式进行读写数据,不会出现oom情况,程序有过高并发场景的验证,因此程序运行比较稳定,相对于 Easypoi 来说,读写性能稍慢!
Easypoi 与 Easyexcel 还有一点区别在于,Easypoi 对定制化的导出支持非常的丰富,如果当前的项目需求,并发量不大、数据量也不大,但是需要导出 excel 的文件样式千差万别,那么我推荐你用 easypoi;反之,使用 easyexcel !
来源:https://blog.csdn.net/qq1808814025/article/details/115294105


猜你喜欢
- 前言:想象一下,有一个服务提供个多个客户端调用,但不是所有客户端都需要全部的返回参数:比如商品列表服务返回商品的所有信息,而订单服务调用商品
- 1 Mybatis-Plus简介Mybatis-Plus 提供了多种方式来执行 SQL,包括使用注解、XML 映射文件和 Lambda 表达
- 因为最近重新看了泛型,又看了些反射,导致我对Object、T(以下代指泛型)、?产生了疑惑。我们先来试着理解一下Object类,学习Java
- 前言LayoutInflater在开发中使用频率很高,但是一直没有太知道LayoutInflater.from(context).infla
- 我使用的版本是SpringBoot 2.6.4可以实现注入不同的库连接或是动态切换库<parent>
- 本文实例为大家分享了Android实现百度地图两点画弧线的具体代码,供大家参考,具体内容如下import android.support.a
- 这篇文章主要介绍了Java判断主机是否能ping通代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要
- 本文实例讲述了Android获取当前已连接的wifi信号强度的方法,是Android程序开发中非常常见的重要技巧。分享给大家供大家参考之用。
- 今晚上在编写udp传输文件的时候发现无法用JSON传输字节数组,试了很多种办法都会报错,最后查资料找到了Base64这个类,这个类可以将字节
- 本文实例为大家分享了C++实现连连看游戏的具体代码,供大家参考,具体内容如下这个项目还是挺不错的,运行后也比较有意思,可以看看。#inclu
- 在看内存管理术语表的时候偶然发现了”Pig in the Python(注:有点像中文里的贪心不足蛇吞象)”的定义,于是便有了这篇文章。表面
- JPA是什么? JPA(Java Persistence API)是Sun官方提出的Java持久化规范. 为Java开发人员提供了一种对象/
- //方法一//须添加对System.Web的引用//using System.Web.Security;/// <summary>
- 运用到的MongoDB支持的C#驱动,当前版本为1.6.0下载地址:https://github.com/mongodb/mongo-csh
- 常量,顾名思义,就是“不会改变的量”。我们平时书写的数字(比如12.85)、字符(比如'F')、字符串(比如"谢谢
- 前言 侧滑的实现方式有很多方式来实现,这次总结的ViewDragHe
- 一、对象与内存控制的知识点1.java变量的初始化过程,包括局部变量,成员变量(实例变量和类变量)。2.继承关系中,当使用的对象引用变量编译
- 前言看 WMS 代码的时候看到了 Handler.runWithScissors 方法,所以来恶补一下public static Windo
- 经典的Java基础面试题集锦,欢迎收藏和分享。问题:如果main方法被声明为private会怎样?答案:能正常编译,但运行的时候会提示”ma
- 1. for循环示例#include <stdio.h>int main(){int i,j;int len=4;for(i=l