学习Apache POI 和EasyExcel
Apache POI 官网:http://poi.apache.org/
什么是PIO?
导入依赖
<!--导入依赖-->
<dependencies>
<!--xls (03)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!--xls (07)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<!--日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.5</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
03 | 07 版本的写,就是对象不同,方法一样的
需要注意:2003版本和2007版本存在兼容性的问题! 03最多只有65535行!
POI Excel 写
03版本:
@Test
public void testWriter03() throws Exception {
// 1.创建一个工作薄
Workbook workbook = new HSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("用户统计表");
// 3.创建一行
Row row1 = sheet.createRow(0);
// 4.创建一个单元格
Cell cell11 = row1.createCell(0);
cell11.setCellValue("今日新增用户");
//(1,2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue(666);
// 3.创建第二行 (2,1)
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
// (2,2)
Cell cell22 = row2.createCell(1);
String time = new DateTime().toString("yyyy-MM-dd HH-mm-ss");
cell22.setCellValue(time);
//生成一张表 io
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户统计表.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("用户表03!生成完毕!");
}
07版本:
@Test
public void testWriter07() throws Exception {
// 1.创建一个工作薄
Workbook workbook = new XSSFWorkbook();
// 2.创建一个工作表
Sheet sheet = workbook.createSheet("用户统计表");
// 3.创建一行
Row row1 = sheet.createRow(0);
// 4.创建一个单元格
Cell cell11 = row1.createCell(0);
cell11.setCellValue("今日新增用户");
//(1,2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue(666);
// 3.创建第二行 (2,1)
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
// (2,2)
Cell cell22 = row2.createCell(1);
String time = new DateTime().toString("yyyy-MM-dd HH-mm-ss");
cell22.setCellValue(time);
//生成一张表 io
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "用户统计表07.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("用户表07!生成完毕!");
}
注意对象的区别,和后缀的区别!
大数据批量写入
大文件写HSSF
缺点:最多只能处理65536,否则会抛出异常
优点:过程中写入缓存,不操作磁盘,最后一次写入磁盘,速度快
@Test
public void testWriter03BigData() throws IOException {
//时间
long begin = System.currentTimeMillis();
//创建一个工作薄
Workbook workbook = new HSSFWorkbook();
//创建一个表
Sheet sheet = workbook.createSheet();
//写入数据
for (int romNum = 0; romNum < 65536; romNum++) {
Row row = sheet.createRow(romNum);
for (int cellNum = 0; cellNum < 10; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("over");
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWriter03BigData.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
long end = System.currentTimeMillis();
System.out.println((double) (end-begin)/1000);
}
大文件写XSSF
缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万条
优点:可以写较大的数据量,如20万条
@Test
public void testWriter03BigData() throws IOException {
//时间
long begin = System.currentTimeMillis();
//创建一个工作薄
Workbook workbook = new XSSFWorkbook();
//创建一个表
Sheet sheet = workbook.createSheet();
//写入数据
for (int romNum = 0; romNum < 100000; romNum++) {
Row row = sheet.createRow(romNum);
for (int cellNum = 0; cellNum < 10; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("over");
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWriter03BigData.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();
long end = System.currentTimeMillis();
System.out.println((double) (end-begin)/1000);
}
POI Excel 读
03 版本读
String PATH = "C:\\Users\\Administrator\\Desktop\\study_poi\\";
@Test
public void testRead03() throws Exception {
//获取流
FileInputStream fileInputStream = new FileInputStream(PATH + "study_poi用户统计表.xls");
// 1.创建一个工作薄
Workbook workbook = new HSSFWorkbook(fileInputStream);
// 获取表
Sheet sheetAt = workbook.getSheetAt(0);
//获取行
Row row = sheetAt.getRow(0);
//获取列
Cell cell = row.getCell(0);
fileInputStream.close();
System.out.println(cell.getStringCellValue());
}
07 版本读
@Test
public void testRead07() throws Exception {
//获取流
FileInputStream fileInputStream = new FileInputStream(PATH + "study_poi用户统计表.xlsx");
// 1.创建一个工作薄
Workbook workbook = new XSSFWorkbook(fileInputStream);
// 获取表
Sheet sheetAt = workbook.getSheetAt(0);
//获取行
Row row = sheetAt.getRow(0);
//获取列
Cell cell = row.getCell(0);
fileInputStream.close();
//getStringCellValues 是获取字符串类型
System.out.println(cell.getStringCellValue());
}
注意获取值的类型
EasyExcel
什么是EasyExcel?
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>
创建对象
@Data
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
测试写:
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. 直接写即可
*/
@Test
public void simpleWrite() {
String PATH = "C:\\Users\\Administrator\\Desktop\\study_poi\\";
// 写法1
String fileName = "EasyTest.xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
// write(fileName,格式类)
// sheet(表名)
// doWrite(数据)
EasyExcel.write(PATH + fileName, DemoData.class).sheet("模板").doWrite(data());
}
Web中的写
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DemoData.class).sheet("模板").doWrite(EasyTest.data());
}
测试读:
public class DemoDataListener extends AnalysisEventListener<DemoData> {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);
/**
* 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
List<DemoData> list = new ArrayList<DemoData>();
/**
* 这个每一条数据解析都会来调用
*
* @param data
* one row value. Is is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(DemoData data, AnalysisContext context) {
LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
list.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (list.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
list.clear();
}
}
/**
* 所有数据解析完成了 都会来调用
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
LOGGER.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
LOGGER.info("{}条数据,开始存储数据库!", list.size());
LOGGER.info("存储数据库成功!");
}
@Test
public void simpleRead() {
String PATH = "C:\\Users\\Administrator\\Desktop\\study_poi\\";
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
// 写法1:
String fileName = PATH+"EasyTest.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
}