目前市面上比较流行的操作Excel
文件工具大致有两个,一个是Apache POI
、另一个是阿里的Easy Excel
,但是POI比较消耗内存,Easy Excel对POI进行了一些优化处理,所以Easy Excel使用更为简单方便,此文将带你学习掌握这两款开发利器!
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
Apache POI官网:https://poi.apache.org/
基本功能:
<dependencies>
<!--xls 03-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!--xls 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.9.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
03版本操作:
package com.zhao;
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.junit.jupiter.api.Test;
import java.io.FileOutputStream;
/**
* @author xiaoZhao
* @date 2022/10/24
* @describe excel写操作
*/
public class ExcelWriteTest {
// 路径
String PATH = "E:\\excel\\test_POI";
@Test
public void testWrite03() throws Exception {
// 1.创建一个工作簿
Workbook workbook = new HSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("学生统计表");
// 3.创建一行
Row row1 = sheet.createRow(0);
// 4.创建一个单元格 (1,1)
Cell cell11 = row1.createCell(0);
cell11.setCellValue("学生姓名");
// (1,2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue("学生年龄");
// 创建第二行
Row row2 = sheet.createRow(1);
// (2,1)
Cell cell21 = row2.createCell(0);
cell21.setCellValue("李四");
// (2,2)
Cell cell22 = row2.createCell(1);
cell22.setCellValue(12);
// 生成一张表 03版本使用xls结尾
FileOutputStream outputStream = new FileOutputStream(PATH + "学生统计03.xls");
workbook.write(outputStream);
// 关闭流
outputStream.close();
System.out.println("《==== 学生统计03.xls 生成完毕 ===》");
}
}
打开生成的文件:
07版本操作:
public void testWrite07() throws Exception {
// 1.创建一个工作簿
Workbook workbook = new XSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("学生统计表");
// 3.创建一行
Row row1 = sheet.createRow(0);
// 4.创建一个单元格 (1,1)
Cell cell11 = row1.createCell(0);
cell11.setCellValue("学生姓名");
// (1,2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue("学生年龄");
// 创建第二行
Row row2 = sheet.createRow(1);
// (2,1)
Cell cell21 = row2.createCell(0);
cell21.setCellValue("李四");
// (2,2)
Cell cell22 = row2.createCell(1);
cell22.setCellValue(12);
// 生成一张表 03版本使用xls结尾
FileOutputStream outputStream = new FileOutputStream(PATH + "学生统计07.xlsx");
workbook.write(outputStream);
// 关闭流
outputStream.close();
System.out.println("《==== 学生统计07.xls 生成完毕 ===》");
}
03版本操作:
public void testWrite03BigData() throws Exception {
long start = System.currentTimeMillis();
// 1.创建一个工作簿
Workbook workbook = new HSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("学生统计表03-大数据");
// 写数据
for (int rowNum = 0; rowNum < 65536; rowNum++) {
Row row = sheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 10; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("==== over ===");
FileOutputStream outputStream = new FileOutputStream(PATH + "学生统计表03-大数据.xls");
workbook.write(outputStream);
outputStream.close();
long edn = System.currentTimeMillis();
System.out.println((double) (edn - start)/1000);
}
07版本操作:
public void testWrite07BigData() throws Exception {
long start = System.currentTimeMillis();
// 1.创建一个工作簿
Workbook workbook = new XSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("学生统计表07-大数据");
// 写数据
for (int rowNum = 0; rowNum < 65536; rowNum++) {
Row row = sheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 10; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("==== over ===");
FileOutputStream outputStream = new FileOutputStream(PATH + "学生统计表07-大数据.xlsx");
workbook.write(outputStream);
outputStream.close();
long edn = System.currentTimeMillis();
System.out.println((double) (edn - start)/1000);
}
07版加速本操作:
public void testWrite07BigDataS() throws Exception {
long start = System.currentTimeMillis();
// 1.创建一个工作簿
Workbook workbook = new SXSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("学生统计表07S-大数据");
// 写数据
for (int rowNum = 0; rowNum < 65536; rowNum++) {
Row row = sheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 10; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("==== over ===");
FileOutputStream outputStream = new FileOutputStream(PATH + "学生统计表07S-大数据.xlsx");
workbook.write(outputStream);
// 删除临时文件
((SXSSFWorkbook)workbook).dispose();
outputStream.close();
long edn = System.currentTimeMillis();
System.out.println((double) (edn - start)/1000);
}
03版本操作:
package com.zhao;
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.junit.jupiter.api.Test;
import java.io.FileInputStream;
/**
* @author xiaoZhao
* @date 2022/10/24
* @describe poi excel读操作
*/
public class ExcelReadTest {
// 路径
String PATH = "E:\\excel\\";
@Test
public void testRead03() throws Exception {
// 获取文件流
FileInputStream inputStream = new FileInputStream(PATH+"test_POI学生统计03.xls");
// 1.创建一个工作簿
Workbook workbook = new HSSFWorkbook(inputStream);
// 得到表
Sheet sheet = workbook.getSheetAt(0);
// 得到行
Row row = sheet.getRow(0);
// 得到列
Cell cell = row.getCell(0);
System.out.println(cell.getStringCellValue());
inputStream.close();
}
}
public void testCellType() throws Exception {
// 获取文件流
FileInputStream inputStream = new FileInputStream(PATH + "明细表.xls");
// 1.创建一个工作簿
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
// 获取标题内容
Row rowTitle = sheet.getRow(0);
if (rowTitle != null) {
int cellCount = rowTitle.getPhysicalNumberOfCells();
for (int cellNum = 0; cellNum < cellCount; cellNum++) {
Cell cell = rowTitle.getCell(cellNum);
if (cell != null) {
CellType cellType = cell.getCellType();
String cellValue = cell.getStringCellValue();
System.out.print(cellValue + " | ");
}
}
System.out.println();
}
// 获取表中内容
int rowCount = sheet.getPhysicalNumberOfRows();
for (int rowNum = 0; rowNum < rowCount; rowNum++) {
Row rowData = sheet.getRow(rowNum);
if (rowData != null) {
// 读取列
int cellCount = rowTitle.getPhysicalNumberOfCells();
for (int cellNum = 0; cellNum < cellCount; cellNum++) {
System.out.print("{" + (rowNum + 1) + "-" + (cellNum + 1) + "}");
Cell cell = rowData.getCell(cellNum);
// 匹配列的数据类型
if (cell != null) {
CellType cellType = cell.getCellType();
String cellValue = "";
switch (cellType) {
case STRING:
System.out.println("String");
cellValue = cell.getStringCellValue();
break;
case BOOLEAN:
System.out.println("boolean");
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case BLANK:
System.out.println("BLANK");
break;
case NUMERIC:
System.out.println("NUMERIC");
break;
case ERROR:
System.out.println("ERROR");
break;
}
System.out.println(cellValue);
}
}
}
}
}
EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。他能让你在不用考虑性能、内存的等因素的情况下,快速完成Excel的读、写等功能。EasyExcel基于POI进行封装优化,降低内存使用,再大的excel也不会出现内存溢出,让使用更加简单方便。
Easy Excel官网:https://easyexcel.opensource.alibaba.com/
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
创建一个Excel表格对象:
@Data
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略字段
**/
@ExcelIgnore
private String ignore;
}
测试代码:
public class EasyTest {
String PATH = "E:\\excel\\test_POI";
private List<DemoData> data() {
List<DemoData> list = ListUtils.newArrayList();
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;
}
// 根据list 写入excel
/**
* 最简单的写
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 直接写即可
*/
@Test
public void simpleWrite() {
String fileName =PATH + "EasyTest.xlsx";
// write(fileName , 格式类)
// sheet(表名)
// doWrite(数据)
EasyExcel.write(fileName, DemoData.class)
.sheet("模板")
.doWrite(data());
}
}
创建一个Excel表格对象:
@Data
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略字段
**/
@ExcelIgnore
private String ignore;
}
创建监听器:
@Slf4j
public class DemoDataListener implements ReadListener<DemoData> {
private static final int BATCH_COUNT = 100;
private List<DemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private DemoDAO demoDAO;
public DemoDataListener() {
demoDAO = new DemoDAO();
}
public DemoDataListener(DemoDAO demoDAO) {
this.demoDAO = demoDAO;
}
@Override
public void invoke(DemoData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
log.info("所有数据解析完成!");
}
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
demoDAO.save(cachedDataList);
log.info("存储数据库成功!");
}
}
测试代码:
@Test
public void simpleRead() {
String fileName =PATH + "EasyTest.xlsx";
EasyExcel.read(fileName, DemoData.class, new PageReadListener<DemoData>(dataList -> {
for (DemoData demoData : dataList) {
System.out.println(JSON.toJSONString(demoData));
}
})).sheet().doRead();
}