POI及EasyExcel学习笔记
组件、工具
POI-Excel概述
Apache POI
- 结构:
- HSSF - 提供读写[Microsoft Excel](https://baike.baidu.com/item/Microsoft Excel)格式档案的功能。
- XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
- HWPF - 提供读写[Microsoft Word](https://baike.baidu.com/item/Microsoft Word)格式档案的功能。
- HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
- HDGF - 提供读写[Microsoft Visio](https://baike.baidu.com/item/Microsoft Visio)格式档案的功能。
easyExcel
官网:https://github.com/alibaba/easyexcel
介绍:
POI-Excel写
创建项目
导入依赖
<!-- xls(03) -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version>
</dependency>
<!-- xls(07) -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version>
</dependency>
<!-- 日期格式化工具 -->
<dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.10.6</version>
</dependency>
<!-- test -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope>
</dependency>
一、Execl概述
03版的xls,最多只能放65536条数据
07版的xlsx,没有数据条数的限制
它们对应的工具类也不相同
工作簿 ==> 工作表
行
列
03版本
String PATH = "C:\\Users\\DingYifan\\Desktop\\PROJECTS\\PoiAndExecl\\";@Test// 03public void testWrite03() throws IOException {// 1.创建一个工作簿(对象)Workbook workbook = new HSSFWorkbook();// 2.创建一个工作表Sheet sheet = workbook.createSheet("赶快去学习!表");// 3.创建一个行 (1,1)Row row1 = sheet.createRow(0);// 4.创建一个单元格Cell cell11 = row1.createCell(0);cell11.setCellValue("今天你学习了吗");Cell cell12 = row1.createCell(1);cell12.setCellValue("今天我学习了吗");Cell cell13 = row1.createCell(2);cell13.setCellValue("今天他学习了吗");// 创建第二个行Row row2 = sheet.createRow(1);Cell cell21 = row2.createCell(0);cell21.setCellValue("今天小狗学习了吗");Cell cell22 = row2.createCell(1);cell22.setCellValue("今天小猫学习了吗");// 日期Cell cell23 = row2.createCell(2);;String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");cell23.setCellValue(time);// 生成一张表(IO流) 03版本就是使用xls结尾!FileOutputStream fileOutputStream = new FileOutputStream(PATH + "阿巴阿巴你学习了吗.xls");// 输出workbook.write(fileOutputStream);// 关闭流fileOutputStream.close();System.out.println("Execl生成完毕");}
07版本
@Test// 07public void testWrite07() throws IOException {// 1.创建一个工作簿(对象)Workbook workbook = new XSSFFWorkbook();// 2.创建一个工作表Sheet sheet = workbook.createSheet("赶快去学习!表");// 3.创建一个行 (1,1)Row row1 = sheet.createRow(0);// 4.创建一个单元格Cell cell11 = row1.createCell(0);cell11.setCellValue("今天你学习了吗");Cell cell12 = row1.createCell(1);cell12.setCellValue("今天我学习了吗");Cell cell13 = row1.createCell(2);cell13.setCellValue("今天他学习了吗");// 创建第二个行Row row2 = sheet.createRow(1);Cell cell21 = row2.createCell(0);cell21.setCellValue("今天小狗学习了吗");Cell cell22 = row2.createCell(1);cell22.setCellValue("今天小猫学习了吗");// 日期Cell cell23 = row2.createCell(2);;String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");cell23.setCellValue(time);// 生成一张表(IO流) 07版本就是使用xlsx结尾!FileOutputStream fileOutputStream = new FileOutputStream(PATH + "阿巴阿巴你学习了吗.xlsx");// 输出workbook.write(fileOutputStream);// 关闭流fileOutputStream.close();System.out.println("Execl生成完毕");
注意对象的一个区别,文件后缀!
数据批量导入!
二、大文件写HSSF
缺点:最多只能处理65536行,否则会抛出异常
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快
03.xls
@Testpublic void testWriteBigdata03() throws IOException {// 时间long begin = System.currentTimeMillis();// 1.创建一个工作簿(对象)Workbook workbook = new HSSFWorkbook();// 2.创建一个工作表Sheet sheet = workbook.createSheet();// 写入数据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 + "Bigdata03.xls");long end = System.currentTimeMillis();workbook.write(outputStream);// 关闭流outputStream.close();System.out.println((double)(end-begin)/1000);}
数据批量导入!
三、大文件写XSSF
缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出(om),如100w条
优点:可以写较大的数据量,如20w条
07.xlsx
@Testpublic void testWriteBigdata07() throws IOException {// 时间long begin = System.currentTimeMillis();// 1.创建一个工作簿(对象)Workbook workbook = new XSSFWorkbook();// 2.创建一个工作表Sheet sheet = workbook.createSheet();// 写入数据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 + "Bigdata07.xlsx");long end = System.currentTimeMillis();workbook.write(outputStream);// 关闭流outputStream.close();System.out.println((double)(end-begin)/1000);}
四、大文件写SXSSF
优点:可以写非常大的数据量,如100w条甚至更多条,写数据速度快,占用更少的内存
注意:
过程中会产生临时文件,需要清理临时文件
默认由100条记录被保存在内存中,如果超过这数量,则最前面的数据被写入临时文件
如果想自定义内存中数据的数量,可以使用 new SXSSFWorkbook(数量)
/*
代码与XSSF相同,只需要改变创建对象
由于会产生临时文件,我们需要在最后把临时文件删除,使用:
((SXSSFWorkbook) workbook).dispose();
*/@Testpublic void testWriteBigdata07_2() throws IOException {// 时间long begin = System.currentTimeMillis();// 1.创建一个工作簿(对象)Workbook workbook = new SXSSFWorkbook();// 2.创建一个工作表Sheet sheet = workbook.createSheet();// 写入数据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 + "Bigdata07.xlsx");long end = System.currentTimeMillis();workbook.write(outputStream);// 关闭流outputStream.close();// 清除临时文件((SXSSFWorkbook) workbook).dispose();System.out.println((double)(end-begin)/1000);}
SXSSFWorkbook-来自官方的解释:
实现”BigGridDemo“策略的流式XSSFWorkbook版本。这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。
请注意,仍然可能会消耗大量内存,这些内存基于您正在使用的功能,例如合并区域,注释…仍然只存储在内存中,因此如果广泛使用,可能需要大量内存
再使用POI的时候,内存问题Jprofile!
POI-Excel写
一、03 | 07
二、读取不同的数据类型
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;@Testpublic void testCellType() throws IOException {// 获取文件流FileInputStream inputStream = new FileInputStream( PATH + "明细表.xls" );// 1.创建一个工作簿(对象):使用execl能操作的这边都可以操作Workbook workbook = new HSSFWorkbook(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.getCellTypeEnum();String cellValue = cell.getStringCellValue();System.out.print(cellValue + " | ");}}System.out.println();}// 获取表中的内容int rowCount = sheet.getPhysicalNumberOfRows();for(int rowNum = 1 ; 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.getCellTypeEnum();String cellValue = " ";if (cell != null) {CellType cellType = cell.getCellTypeEnum();switch (cellType) {case STRING:System.out.print("【String类型】");cellValue = cell.getStringCellValue();break;case _NONE:System.out.print("【_NONE类型】");cellValue = String.valueOf(cell.getStringCellValue());break;case FORMULA:System.out.print("【FORMULA类型】");break;case BLANK:System.out.print("【BLANK类型】");cellValue = String.valueOf(cell.getStringCellValue());break;case BOOLEAN:System.out.print("【BOOLEAN类型】");cellValue = String.valueOf(cell.getBooleanCellValue());break;case NUMERIC:System.out.print("【NUMERIC类型】");if(HSSFDateUtil.isCellDateFormatted(cell)){// 日期System.out.print("【日期】");Date date = cell.getDateCellValue();new DateTime(date).toString("yyyy-MM-dd");}else{// 如果不是日期格式,防止数字过长(科学计数法)System.out.print("【转换为字符串输出】");cell.setCellType(CellType.STRING);cellValue = cell.toString();}break;case ERROR: // 错误System.out.print("【ERROR类型】");break;}System.out.println(cellValue);}}}}inputStream.close();}}
需要注意类型转换问题
将代码提取成Java工具类:将inputStream变成参数
@Testpublic void testCellType(FileInputStream inputStream) throws IOException {// 获取文件流:直接传进来就可以// FileInputStream inputStream = new FileInputStream( PATH + "明细表.xls" );// 1.创建一个工作簿(对象):使用execl能操作的这边都可以操作Workbook workbook = new HSSFWorkbook(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.getCellTypeEnum();String cellValue = cell.getStringCellValue();System.out.print(cellValue + " | ");}}System.out.println();}// 获取表中的内容int rowCount = sheet.getPhysicalNumberOfRows();for(int rowNum = 1 ; 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.getCellTypeEnum();String cellValue = " ";if (cell != null) {CellType cellType = cell.getCellTypeEnum();switch (cellType) {case STRING:System.out.print("【String类型】");cellValue = cell.getStringCellValue();break;case _NONE:System.out.print("【_NONE类型】");cellValue = String.valueOf(cell.getStringCellValue());break;case FORMULA:System.out.print("【FORMULA类型】");break;case BLANK:System.out.print("【BLANK类型】");cellValue = String.valueOf(cell.getStringCellValue());break;case BOOLEAN:System.out.print("【BOOLEAN类型】");cellValue = String.valueOf(cell.getBooleanCellValue());break;case NUMERIC:System.out.print("【NUMERIC类型】");if(HSSFDateUtil.isCellDateFormatted(cell)){// 日期System.out.print("【日期】");Date date = cell.getDateCellValue();new DateTime(date).toString("yyyy-MM-dd");}else{// 如果不是日期格式,防止数字过长(科学计数法)System.out.print("【转换为字符串输出】");cell.setCellType(CellType.STRING);cellValue = cell.toString();}break;case ERROR: // 错误System.out.print("【ERROR类型】");break;}System.out.println(cellValue);}}}}inputStream.close();}}
三、计算公式
@Testpublic void testFormula() throws Exception {FileInputStream inputStream = new FileInputStream(PATH + "公式.xls");Workbook workbook = new HSSFWorkbook(inputStream);Sheet sheet = workbook.getSheetAt(0);Row row = sheet.getRow(4);Cell cell = row.getCell(0);// 拿到计算公式 evalFormulaEvaluator FormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook)workbook);// 输出单元格的内容CellType cellType = cell.getCellTypeEnum();switch(cellType){case FORMULA: // 公式String formula = cell.getCellFormula();System.out.println(formula);// 计算CellValue evaluate = FormulaEvaluator.evaluate(cell);String cellValue = evaluate.formatAsString();System.out.println(cellValue);break;}}
EasyExcel操作
一、导入依赖
首先要去掉poi的依赖,因为它内置了该依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version>
</dependency>
二、写入测试
1、DemoData.java
2、测试写入数据
最终的结果:
三、读取测试
http://www.yuque.com/easyexcel/doc/read
EasyExcel总结笔记
读excel
step 01 导入依赖
-
pom文件中导入依赖
-
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope> </dependency> <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version> </dependency>
step 02 写实体类
-
java \ com \ ding \ 实体类名 \ DemoData
-
创建对象 ==> 创建实体层
-
@Data public class DemoData {private String string;private Date date;private Double doubleData; }
step 03 写测试类
写excel
step 01 导入依赖
-
pom文件中导入依赖
-
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope> </dependency> <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version> </dependency>
step 02 写实体类
-
java \ com \ ding \ 实体类名 \ DemoData
-
创建对象 ==> 创建实体层
-
@Data public class DemoData {private String string;private Date date;private Double doubleData; }
step 03 写测试类
-
业务逻辑层 ==> 写一个测试类
-
通用数据生成
-
public class EasyTest{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;}// 写值代码/*** 最简单的写* <p>1. 创建excel对应的实体对象 参照{@link DemoData}* <p>2. 直接写即可*/@Testpublic void simpleWrite() {// 写法1String fileName = "生成测试文件.xlsx";// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());}}
-
方法返回一个list,我们要根据list写值,写入excel
-
EasyExcel.write() 方法
-
wirte ( fileName,格式类 )
-
sheet ( 表名 )
-
doWrite ( 数据 )
-
EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
-
附录
一些问题
01 关于POI 操作 Excel 中 HSSFCell.CELL_TYPE_STRING 等无定义解决方法
一、错误原因:jar包版本更新,官方改动;
二、解决方案:导入CellType包import org.apache.poi.ss.usermodel.CellType;使用CellType.STRING代替HSSFCell.CELL_TYPE_STRING
三、旧版代码:
/*** excel值处理* @param hssfCell* @return*/public static Object getXSSFValue(XSSFCell hssfCell) {if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {return hssfCell.getNumericCellValue(); //数字}else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {return hssfCell.getBooleanCellValue(); //boolean}else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_ERROR){return hssfCell.getErrorCellValue(); //故障}else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_FORMULA){return hssfCell.getCellFormula(); //公式}else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_BLANK) {return ""; //空值}else {return hssfCell.getStringCellValue(); //字符串}}/*** excel值处理* @param hssfCell* @return*/public static Object getValue(Cell hssfCell) {if(hssfCell.getCellType()==XSSFCell.CELL_TYPE_NUMERIC) {return hssfCell.getNumericCellValue(); //数字 }else if(hssfCell.getCellType()==XSSFCell.CELL_TYPE_BOOLEAN) {return hssfCell.getBooleanCellValue(); //boolean}else if(hssfCell.getCellType()==XSSFCell.CELL_TYPE_ERROR){return hssfCell.getErrorCellValue(); //故障}else if(hssfCell.getCellType()==XSSFCell.CELL_TYPE_FORMULA){return hssfCell.getCellFormula(); //公式}else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_BLANK) {return ""; //空值}else {return hssfCell.getStringCellValue(); //字符串}}
四、新版代码:
/*** excel值处理** @param hssfCell* @return*/public static Object getXSSFValue(XSSFCell hssfCell) {Object result = null;CellType cellType = hssfCell.getCellType();switch (hssfCell.getCellType()) {case NUMERIC: //数字result = hssfCell.getNumericCellValue();break;case BOOLEAN: //Booleanresult = hssfCell.getBooleanCellValue();break;case ERROR: //故障result = hssfCell.getErrorCellValue();break;case FORMULA: //公式result = hssfCell.getCellFormula();break;case BLANK: //空值result = "";break;default: //字符串result = hssfCell.getStringCellValue();}return result;}/*** excel值处理** @param hssfCell* @return*/public static Object getValue(Cell hssfCell) {Object result = null;switch (hssfCell.getCellType()) {case NUMERIC: //数字result = hssfCell.getNumericCellValue();break;case BOOLEAN: //Booleanresult = hssfCell.getBooleanCellValue();break;case ERROR: //故障result = hssfCell.getErrorCellValue();break;case FORMULA: //公式result = hssfCell.getCellFormula();break;case BLANK: //空值result = "";break;default: //字符串result = hssfCell.getStringCellValue();}return result;}
固定套路:
1、写入,固定类格式进行写入
2、读取,根据监听器设置的规则进行读取
了解,面向对象的思想,面向接口编程
理解使用测试API
官方文档的API进行自己的测试并进行总结