POI操作Excel
常用场景
1、将用户信息导出为excel表格(导出数据… )
2、将Excel表中的信息录入到网站数据库(文件数据上传… )
开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中!
操作Excel目前比较流行的就是Apache POI 和 阿里巴巴的 Easyexcel!
Apache POI
Apache POI 官网地址:https://poi.apache.org/会比较麻烦,比较消耗内存出现OOM(内存溢出异常)
EasyExcel
EasyExcel官网地址:https://github.com/alibaba/easyexcel
EasyExcel 是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称。
EasyExcel 能大大减少占用内存的主要原因是在解析 Excel 时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。
内存问题:POI = 100w先加载到内存 OOM。。写入文件 es = 1
下图是 EasyExcel 和 POI 在解析Excel时的对比图。
EasyExcel 使用POI的sax模式一行一行解析,并将一行的解析结果以观察者的模式通知处理。
官方文档:https://www.yuque.com/easyexcel/doc/easyexcel
POI操作Excel
POI-Excel写
创建项目
1、创建一个空项目test,创建普通Maven的Moudle demo-poi
2、引入依赖
<dependencies>
<!--xls(03)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!--xls(07)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!--日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
03 | 07 版本的写,就是对象不同,方法一样的!
需要注意:2003版本和2007版本存在兼容性的问题!03最多只能有65536行!而07最多只能有1048576行!
1、工作簿:Workbook
2、工作表:Sheet
3、行:Row
4、列:Cell
03版本:
// 1、创建一个工作簿
Workbook workbook = new HSSFWorkbook();
// 2、创建一个工作表
Sheet sheet = workbook.createSheet("角色统计表");
// 3、创建一个行 (1,1)
Row row1 = sheet.createRow(0);
// 4、创建一个单元格
Cell cell1 = row1.createCell(0);
cell1.setCellValue("角色名称");
// (1,2)
Cell cell2 = row1.createCell(1);
cell2.setCellValue("角色性别");
// (1,3)
Cell cell3 = row1.createCell(2);
cell3.setCellValue("角色创建时间");
// 创建第二行 (2,1)
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("神里凌华");
// (2,2)
Cell cell22 = row2.createCell(1);
cell22.setCellValue("女");
// (2,3)
Cell cell23 = row2.createCell(2);
String time = new DateTime().toString("yyyy-mm-dd HH:mm:ss");
cell23.setCellValue(time);
String PATH = "D:/桌面/test/";
// 生成一张表 (IO 流) 03 版本就是使用 xls结尾!
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "角色统计表03.xls");
// 将IO流写入到Excel中
workbook.write(fileOutputStream);
// 刷新输出流
fileOutputStream.flush();
// 关闭输出流
fileOutputStream.close();
System.out.println("角色统计表03 生成完毕");
运行结果如下:
07版本:
// 1、创建一个工作簿
Workbook workbook = new XSSFWorkbook();
// 2、创建一个工作表
Sheet sheet = workbook.createSheet("角色统计表");
// 3、创建一个行 (1,1)
Row row1 = sheet.createRow(0);
// 4、创建一个单元格
Cell cell1 = row1.createCell(0);
cell1.setCellValue("角色名称");
// (1,2)
Cell cell2 = row1.createCell(1);
cell2.setCellValue("角色性别");
// (1,3)
Cell cell3 = row1.createCell(2);
cell3.setCellValue("角色创建时间");
// 创建第二行 (2,1)
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("神里凌华");
// (2,2)
Cell cell22 = row2.createCell(1);
cell22.setCellValue("女");
// (2,3)
Cell cell23 = row2.createCell(2);
String time = new DateTime().toString("yyyy-mm-dd HH:mm:ss");
cell23.setCellValue(time);
String PATH = "D:/桌面/test/";
// 生成一张表 (IO 流) 07 版本就是使用 xlsx结尾!
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "角色统计表07.xlsx");
// 将IO流写入到Excel中
workbook.write(fileOutputStream);
// 刷新输出流
fileOutputStream.flush();
// 关闭输出流
fileOutputStream.close();
System.out.println("角色统计表07 生成完毕");
运行结果如下:
注意对象的区别,文件后缀!
大文件写HSSF
缺点:最多只能处理65536行,否则会抛出异常
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度块
// 开始时间
long begin = System.currentTimeMillis();
// 创建一个簿
Workbook workbook = new HSSFWorkbook();
// 创建表
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");
String PATH = "D:/桌面/test/";
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "BigData03.xls");
workbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
// 结束时间
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
运行结果如下:
大文件写XSSF
缺点:写数据时速度非常慢,非常消耗内存,也会发生内存溢出,如100万条
优点:可以写较大的数据量,如20万条
// 开始时间
long begin = System.currentTimeMillis();
// 创建一个簿
Workbook workbook = new XSSFWorkbook();
// 创建表
Sheet sheet = workbook.createSheet();
//写入数据
for (int rowNum = 0; rowNum < 100000; 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 fileOutputStream = new FileOutputStream(PATH + "BigData07.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
// 结束时间
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
运行结果如下:
大文件写SXSSF
优点:可以写非常大的数据量,如100万条甚至更多条,写数据速度快,占用更少内存
注意:
过程中会产生临时文件,需要清理临时文件
默认由100条记录会被保存在内存中,如果超过这个数量,则最前面的数据被写入临时文件
如果想自定义内存中数据的数量,可以使用new SXSSFWorkbook(数量)
// 开始时间
long begin = System.currentTimeMillis();
// 创建一个簿
Workbook workbook = new SXSSFWorkbook();
// 创建表
Sheet sheet = workbook.createSheet();
//写入数据
for (int rowNum = 0; rowNum < 100000; 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 fileOutputStream = new FileOutputStream(PATH + "BigData07S.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
// 清除临时文件
((SXSSFWorkbook) workbook).dispose();
// 结束时间
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
运行结果如下:
SXSSFWorkbook-来至官方的解释:实现"BigGridDemo"策略的流式XSSFWorkbook版本。这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。
请注意,仍然可能会消耗大量内存,这些内存基于您正在使用的功能,例如合并区域,注释…仍然只存储在内存中,因此如果广泛使用,可能需要大量内存。
再使用 POI的时候!内存问题Jprofile !
POI-Excel读
03 | 07
03版本
String PATH = "D:/桌面/test/";
// 获取文件流
FileInputStream fileInputStream = new FileInputStream(PATH + "角色统计表03.xls");
// 1、创建一个工作簿。使用excel能操作的这边他都可以操作!
Workbook workbook = new HSSFWorkbook(fileInputStream);
// 2、通过工作簿获取工作表,表中的设置
Sheet sheet = workbook.getSheetAt(0);
// 获得行
Row row = sheet.getRow(0);
// 获得列
Cell cell = row.getCell(3);
// 读取值的时候,一定需要注意数据类型
// getStringCellValue 字符串类型
// System.out.println(cell.getStringCellValue());
System.out.println(cell.getNumericCellValue());
// 关闭文件流
fileInputStream.close();
运行结果如下:
07版本
String PATH = "D:/桌面/test/";
// 获取文件流
FileInputStream fileInputStream = new FileInputStream(PATH + "角色统计表07.xlsx");
// 1、创建一个工作簿。使用excel能操作的这边他都可以操作!
Workbook workbook = new XSSFWorkbook(fileInputStream);
// 2、通过工作簿获取工作表,表中的设置
Sheet sheet = workbook.getSheetAt(0);
// 获得行
Row row = sheet.getRow(0);
// 获得列
Cell cell = row.getCell(2);
// 读取值的时候,一定需要注意数据类型
// getStringCellValue 字符串类型
System.out.println(cell.getStringCellValue());
// 关闭文件流
fileInputStream.close();
运行结果如下:
注意获取列的数据类型即可
读取不同的类型数据(最麻烦的就是这里了!)
Java代码如:
String PATH = "D:/桌面/test/";
// 读取文件流
FileInputStream fileInputStream = new FileInputStream(PATH + "明细表.xlsx");
// 获取工作簿
Workbook workbook = new XSSFWorkbook(fileInputStream);
// 获取工作表
Sheet sheet = workbook.getSheetAt(0);
// 获取标题内容
Row rowTile = sheet.getRow(0);
if (rowTile != null) {
int cellCount = rowTile.getPhysicalNumberOfCells();
for (int cellNum = 0; cellNum < cellCount; cellNum++) {
Cell cell = rowTile.getCell(cellNum);
if (cell != null) {
int cellType = cell.getCellType();
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 = rowData.getPhysicalNumberOfCells();
for (int cellNum = 0; cellNum < cellCount; cellNum++) {
System.out.print("[" + (rowNum + 1) + "-" + (cellNum + 1) + "]");
Cell cell = rowData.getCell(cellNum);
// 匹配列的数据类型
if (cell != null) {
int cellType = cell.getCellType();
String cellValue = "";
switch (cellType) {
case XSSFCell.CELL_TYPE_STRING: // 字符串
System.out.print("【String】");
cellValue = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BOOLEAN: // 布尔
System.out.print("【Boolean】");
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_BLANK: // 空的
System.out.print("【Blank】");
break;
case XSSFCell.CELL_TYPE_NUMERIC: // 数字(日期、普通数字)
System.out.print("【numeric】");
if (DateUtil.isCellDateFormatted(cell)) { // 日期
System.out.print("【日期】");
Date date = cell.getDateCellValue();
cellValue = new DateTime(date).toString("yyyy-MM-dd");
} else {
// 不是日期格式,防止数字过长
System.out.print("【转行为字符串输出】");
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cellValue = cell.toString();
}
break;
case XSSFCell.CELL_TYPE_ERROR: // 错误
System.out.print("【数据类型错误】");
break;
}
System.out.println(cellValue);
}
}
}
}
fileInputStream.close();
运行结果如下:
注意类型转换问题:
计算公式(了解即可)
Java代码如下:
String PATH = "D:/桌面/test/";
FileInputStream fileInputStream = new FileInputStream(PATH + "公式表.xlsx");
Workbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(4);
Cell cell = row.getCell(0);
// 拿到计算公式 eval
FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
// 输出单元格的内容
int cellType = cell.getCellType();
switch (cellType) {
case XSSFCell.CELL_TYPE_FORMULA: // 公式
String formula = cell.getCellFormula();
System.out.println(formula);
//计算
CellValue evaluate = formulaEvaluator.evaluate(cell);
System.out.println(evaluate);
String cellValue = evaluate.formatAsString();
System.out.println(cellValue);
}
运行结果如下: