Java 操作 Excel 之 POI 与 EasyExcel
发表于更新于
字数总计:2.8k阅读时长:12分钟阅读量: 上海
前言
在工作中,使用 excel 表格处理数据是很常见的操作,作为一个 Java 开发工程师,学会使用 Java 来操作 excel 表格是必备的技能之一。
本文就通过市面上常用的两种方式来实现 Java 对 excel 表格的操作:
- Apache POI
- Alibaba EasyExcel
一、Apache POI
简介
Apache POI 官网: https://poi.apache.org/
POI 是目前比较流行的 Java 处理 excel 框架,但是其缺点是 数据量大容易造成 OOM 异常
基本结构
快速开始
创建 一个空项目,在空项目中新建一个 module 模块:一个普通的 maven 项目即可
1、导入 pom 依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <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.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
|
2、POI 写入 Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| package com.lxki;
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 org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.joda.time.DateTime; import org.junit.Test;
import java.io.FileOutputStream;
public class WriteExcelTest {
private static final String PATH = "E:\\workspace\\IdeaProjects\\POI-EasyExcel\\lxki-poi\\";
@Test public void testWrite03() throws Exception { Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("员工信息表03");
Row row1 = sheet.createRow(0); Cell cell11 = row1.createCell(0); cell11.setCellValue("姓名"); Cell cell12 = row1.createCell(1); cell12.setCellValue("张三");
Row row2 = sheet.createRow(1); Cell cell21 = row2.createCell(0); cell21.setCellValue("出生日期"); Cell cell22 = row2.createCell(1); cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "员工信息表03.xls"); workbook.write(fileOutputStream);
fileOutputStream.close(); System.out.println("员工信息表03.xls ==> 输出完毕"); }
@Test public void testWrite07() throws Exception { Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("员工信息表07");
Row row1 = sheet.createRow(0); Cell cell11 = row1.createCell(0); cell11.setCellValue("姓名"); Cell cell12 = row1.createCell(1); cell12.setCellValue("张三");
Row row2 = sheet.createRow(1); Cell cell21 = row2.createCell(0); cell21.setCellValue("出生日期"); Cell cell22 = row2.createCell(1); cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "员工信息表07.xlsx"); workbook.write(fileOutputStream);
fileOutputStream.close(); System.out.println("员工信息表07.xls ==> 输出完毕"); } }
|
3、POI 读取 Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| package com.lxki;
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 org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test;
import java.io.FileInputStream;
public class ReadExcelTest {
private static final String PATH = "E:\\workspace\\IdeaProjects\\POI-EasyExcel\\lxki-poi\\";
@Test public void testRead03() throws Exception{ FileInputStream fileInputStream = new FileInputStream(PATH + "员工信息表03.xls");
Workbook workbook = new HSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0); int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 0; rowNum < rowCount; rowNum++) { Row row = sheet.getRow(rowNum); int cellCount = row.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { Cell cell = row.getCell(cellNum); System.out.print(cell.getStringCellValue()+"\t"); } System.out.println(); } }
@Test public void testRead07() throws Exception{ FileInputStream fileInputStream = new FileInputStream(PATH + "员工信息表07.xlsx");
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0); int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 0; rowNum < rowCount; rowNum++) { Row row = sheet.getRow(rowNum); int cellCount = row.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { Cell cell = row.getCell(cellNum); System.out.print(cell.getStringCellValue()+"\t"); } System.out.println(); } }
}
|
注意:
03
和 07
版本的 excel
表格对应的 POI 操作 API 是不同的(HSSF
与 XSSF
)
03
版本最多支持 65536
行数据,而 07
则没有限制
HSSF
操作响应速度快于 XSSF
, XSSF
可以使用 SXSSF
替换来提升响应数据
- ==读取
excel
表格中的数据时要注意判断不同的数据类型,使用对应的读取方法==
最终的项目目录结构:
二、EasyExcel
简介
EasyExcel 官网地址:https://github.com/alibaba/easyexcel
EasyExcel 是 Alibaba 开源的一个 excel 处理框架,特点是 使用简单、节约内存。
快速开始
在空项目中新建一个新的 module 模块,类型为普通的 maven 项目
1、导入 pom 依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.10</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.72</version> </dependency> </dependencies>
|
2、数据实体对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package com.lxki;
import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data;
import java.util.Date;
@Data public class DemoData { @ExcelProperty("字符串标题") private String string; @ExcelProperty("日期标题") private Date date; @ExcelProperty("数字标题") private Double doubleData;
@ExcelIgnore private String ignore; }
|
3、EasyExcel 写入 Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package com.lxki;
import com.alibaba.excel.EasyExcel; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.Date; import java.util.List;
public class EasyExcelWrite {
private static final String PATH = "E:\\workspace\\IdeaProjects\\POI-EasyExcel\\lxki-easyexcel\\";
private List<DemoData> data() { List<DemoData> list = new ArrayList<DemoData>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setString("字符串" + i); data.setDate(new Date()); data.setDoubleData(0.56); list.add(data); } return list; }
@Test public void simpleWrite() {
String fileName = PATH + "easyexcel07.xlsx"; EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
} }
|
4、EasyExcel 读取 Excel
数据持久层:
1 2 3 4 5 6 7 8 9 10 11 12
| package com.lxki;
import java.util.List;
public class DemoDAO { public void save(List<DemoData> list) { } }
|
读取监听器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.lxki;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.List;
public class DemoDataListener extends AnalysisEventListener<DemoData> { private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);
private static final int BATCH_COUNT = 5; List<DemoData> list = new ArrayList<DemoData>();
private DemoDAO demoDAO; public DemoDataListener() { demoDAO = new DemoDAO(); } public DemoDataListener(DemoDAO demoDAO) { this.demoDAO = demoDAO; }
@Override public void invoke(DemoData data, AnalysisContext context) { LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data)); System.out.println(JSON.toJSONString(data)); list.add(data); if (list.size() >= BATCH_COUNT) { saveData(); list.clear(); } }
@Override public void doAfterAllAnalysed(AnalysisContext context) { saveData(); LOGGER.info("所有数据解析完成!"); }
private void saveData() { LOGGER.info("{}条数据,开始存储数据库!", list.size()); demoDAO.save(list); LOGGER.info("存储数据库成功!"); } }
|
读取测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package com.lxki;
import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelReader; import com.alibaba.excel.read.metadata.ReadSheet; import org.junit.jupiter.api.Test;
import java.io.File;
public class EasyExcelRead {
private static final String PATH = "E:\\workspace\\IdeaProjects\\POI-EasyExcel\\lxki-easyexcel\\";
@Test public void simpleRead() { String fileName = PATH + "easyexcel07.xlsx"; EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead(); } }
|
注意:
- 如果需要操作
03
版本的 excel
,需要在读写操作时传入 excelType
参数
最终的项目结构: