全文内容来自官方文档和相关视频的讲解,本作者用做笔记!
常用场景:
- 将用户信息导出为Excel表格(导出xls数据…)
- 将Excel表中的信息录入到网站数据库(习题上传…公司找老师填写题目到excel再上传网站,网站会利用相关POI将数据回填到数据库,这样大大减轻网站录入量。)
开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中! 操作Excel目前流行的就是Apache POI 和 阿里巴巴 EasyExcel!
Apache POI
Apache POI 官网:
Apache POI 官网:https://poi.apache.org/
??Apache POI 是Apache软件基金会的开放源码函数库,用Java编写的免费开源的跨平台的 Java API。Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
基本功能:
HSSF - 提供读写Microsoft Excel XLS格式档案的功能。 XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。 HWPF - 提供读写Microsoft Word DOC格式档案的功能。 HSLF - 提供读写Microsoft PowerPoint格式档案的功能。 HDGF - 提供读Microsoft Visio格式档案的功能。 HPBF - 提供读Microsoft Publisher格式档案的功能。 HSMF - 提供读Microsoft Outlook格式档案的功能。
Excel 版本区别:03版和07版
03版本 2003版本.xls :行数只有65535行,多了放不了。 07版本 2007版本.xlsx :无限制
POI-Excel 写
创建普通Maven项目:
Java版本:1.8
创建完项目,导入依赖 pom.xml:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
Java编程,万物皆对象:
excel 表中的各个对象: 工作簿、工作表、行、列、单元格
实现类,写入
先创建工作簿,后创建工作表,再有行和列,最后组成了数据:
public class ExcelWriteTest {
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/data/" ;
@Test
public void testWrite03() throws Exception{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("guo1");
Row row11 = sheet.createRow(0);
Cell cell11 = row11.createCell(0);
cell11.setCellValue("今日人数");
Row row12 = sheet.createRow(1);
Cell cell12 = row12.createCell(0);
cell12.setCellValue(666);
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
Cell cell22 = row2.createCell(1);
String time = new DateTime().toString("yyyy-mm-dd HH:mm:ss");
cell22.setCellValue(time);
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "03版本统计表.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("03版本统计表.xls 生成完毕!");
}
}
public class ExcelWriteTest {
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/data/" ;
@Test
public void testWrite07() throws Exception{
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("guo2");
Row row11 = sheet.createRow(0);
Cell cell11 = row11.createCell(0);
cell11.setCellValue("今日人数");
Row row12 = sheet.createRow(1);
Cell cell12 = row12.createCell(0);
cell12.setCellValue(666);
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
Cell cell22 = row2.createCell(1);
String time = new DateTime().toString("yyyy-mm-dd HH:mm:ss");
cell22.setCellValue(time);
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "07版本统计表.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("07版本统计表.xlsx 生成完毕!")
}
}
03与07差别只有文件后缀不同!
数据批量写入:大文件写入HSSF (03版)
缺点:最多只能处理65536行,否则会抛出异常
java.lang.11legalArgumentException : Invalid row number (65536) outside allowable range (0..65535)
优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快。
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/data/" ;
@Test
public void testWrite03BigData() throws IOException {
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");
FileOutputStream outputStream = new FileOutputStream(PATH + "testWrite03BigDATA.xls" );
workbook.write(outputStream);
outputStream.close();
long end = System.currentTimeMillis();
System.out.println((double)(end - begin)/1000);
}
大文件写入HSSF (07版)
缺点: 写数据时速度非常慢,非常耗内存,可能会发生内存溢出,如100万条。 优点,可以写入较大的数据量,如20万条数据。
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/data/" ;
@Test
public void testWrite07BigData() throws IOException {
long begin = System.currentTimeMillis();
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
for( int rowNum = 0; rowNum < 1000000; 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 + "testWrite07BigDATA.xlsx" );
workbook.write(outputStream);
outputStream.close();
long end = System.currentTimeMillis();
System.out.println((double)(end - begin)/1000);
}
大文件写SXSSF (比07版,速度更快)
优点:可以写非常大的数据量,如100万条甚至更多条,写数据速度快,占用更少的内存。 注意:过程中会产生临时文件,需要清理临时文件 原理:默认由100条记录保存在内存中,如果超出这数量,则最前面的数据最前面的数据被写入临时文件,如果想自定义内存中的数据的数量,可以使用new SXSSFWorkbook(数量) SXSSFWorkbook 来至官方的解释,实现“BigGridDemo“策略的流式XSSFWorkbook版本,这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。 请注意,仍然可能会消耗大量内存,这些内存基于您正在使用的功能,例如合并区域,注释,仍然只能存储在内存中,因此如果广泛使用,可能需要大量内存。
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/data/" ;
@Test
public void testWrite07BigDataS() throws IOException{
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 outputStream = new FileOutputStream(PATH + "testWrite07BigDATAS.xlsx" );
workbook.write(outputStream);
outputStream.close();
((SXSSFWorkbook)workbook).dispose();
long end = System.currentTimeMillis();
System.out.println((double)(end - begin)/1000);
}
POI-Excel 读
workbook.createCellStyle();
workbook.createName();
workbook.findFont();
workbook.getAllPictures();
workbook.isHidden();
workbook.removeName();
sheet.createRow();
sheet.autoSizeColumn();
sheet.getColumnWidth();
sheet.getDefaultRowHeightInPoints();
03版本,读数据:
@Test。
public void testRead03() throws Exception{
FileInputStream inputStream = new FileInputStream(PATH +"guo_poi03版本统计表.xls");
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();
}
07版本,读数据:
@Test
public void testRead07() throws Exception{
FileInputStream inputStream = new FileInputStream(PATH +"guo_poi07版本统计表.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell.getNumericCellValue());
inputStream.close();
}
注意获取值的类型;
读取不同数据类型:(最麻烦)注意类型转换
@Test
public void testCellType() throws Exception{
FileInputStream inputStream = new FileInputStream(PATH +"会员消费商品明细表.xls");
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.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 cellCoumt = rowTitle.getPhysicalNumberOfCells();
for (int cellNum = 0;cellNum < cellCoumt ; cellNum++){
System.out.print("["+(rowNum+1)+"-"+(rowNum+1)+"]");
Cell cell = rowData.getCell(cellNum);
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 _NONE:
System.out.print("[NONE]");
break;
case NUMERIC:
System.out.print("[NUMERIC]");
if(DateUtil.isCellInternalDateFormatted(cell)) {
System.out.print("[日期]");
Date date = cell.getDateCellValue();
cellValue = new DateTime(date).toString("yyyy-MM-dd");
}else{
System.out.print("[转换为字符串输出]");
cellValue = cell.toString();
}
break;
case ERROR:
System.out.print("【数据类型错误】");
break;
}
System.out.println(cellValue);
}
}
}
}
inputStream.close();
}
@Test
public void testCellType(FileInputStream inputStream) throws Exception{
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.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 cellCoumt = rowTitle.getPhysicalNumberOfCells();
for (int cellNum = 0;cellNum < cellCoumt ; cellNum++){
System.out.print("["+(rowNum+1)+"-"+(rowNum+1)+"]");
Cell cell = rowData.getCell(cellNum);
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 _NONE:
System.out.print("[NONE]");
break;
case NUMERIC:
System.out.print("[NUMERIC]");
if(DateUtil.isCellInternalDateFormatted(cell)) {
System.out.print("[日期]");
Date date = cell.getDateCellValue();
cellValue = new DateTime(date).toString("yyyy-MM-dd");
}else{
System.out.print("[转换为字符串输出]");
cellValue = cell.toString();
}
break;
case ERROR:
System.out.print("【数据类型错误】");
break;
}
System.out.println(cellValue);
}
}
}
}
inputStream.close();
}
读取并计算公式:
表格样式:
@Test
public 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);
FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook)workbook);
CellType cellType = cell.getCellType();
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
EasyExcel:快速、简洁、解决大文件内存溢出的java处理Excel工具
POI一般底层仍会使用,弊端就是当数据量大的时候会报OOM异常,相比较POI相对简单一些!
EasyExcel : EasyExcel官方地址:https://github.com/alibaba/easyexcel
官方简介: Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便
GitHub EasyExcel :
官方文档:
官方文档:https://www.yuque.com/easyexcel/doc/easyexcel
EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存存储著称。 EasyExcel 能大大减少占用内存的主要原因是在解析Excel是没有将数据一次性全部加载到内存中,而且是从磁盘上一行行读取数据,逐个解析。 内存问题:POI = 100w先加载到内存中(十分耗内存)再一次性写入文件中,当内存不够时可能会报OOM。而EasyExcel在写入文件中是通过磁盘一行一行读取的。 下图是EasyExcel和POI在解析Excel时的对比图。
pom.xml 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
实体类:EasyExcel会根据实体类自动生成表
package easy;
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;
}
实现类:写数据
package easy;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class TestExcel {
String PATH = "/Users/**/Documents/IdeaProjects/guo_poi/src/main/resources/" ;
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;
}
@Test
public void simpleWrite() {
String fileName = PATH + "dataEasyTest.xlsx";
EasyExcel.write(fileName, DemoData.class)
.sheet("模板")
.doWrite(() -> {
return data();
});
}
}
成功运行:可以看到生成了dataEasyExcel.xlsx 生成的数据
实现类:读数据
@Test
public void simpleRead() {
String fileName = PATH + "dataEasyExcel.xlsx";
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
}
持久层:DAO
package easy;
import java.util.List;
public class DemoDAO {
public void save(List<DemoData> list) {
}
}
DemoDataListener:
package easy;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class DemoDataListener extends AnalysisEventListener<DemoData> {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);
private static final int BATCH_COUNT = 5;
private 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) {
System.out.println(JSON.toJSONString(data));
list.add(data);
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
private void saveData() {
log.info("{}条数据,开始存储数据库!", list.size());
demoDAO.save(list);
log.info("存储数据库成功!");
}
}
固定套路:
1. 写入,固定类格式的进行写入! 2. 读取,根据监听器设置的规则进行读取! 一切代码都在官方文档
官方文档: 官方文档:https://www.yuque.com/easyexcel/doc/easyexcel
|