导入POI-Excel
springboot项目引入下面jar包即可
joda-time
joda-time
2.10.1
org.apache.poi
poi
RELEASE
org.apache.poi
poi-ooxml
RELEASE
junit
junit
RELEASE
POI-Excel写
Excel03版本和07版本的区别很小,只需要在new的时候确定new HSSFWorkbook(03)还是new XSSFWorkbook(07)
最后生成文件名时,我们把后缀由xls改成xlsx
public class WriteTest {
String path = "D:\\excel\\src\\main\\java\\com\\lt\\POIExcel";
@Test
public void testWrite01() throws IOException {
//创建新的Excel工作簿03版本
//Workbook workbook = new HSSFWorkbook();
//创建新的Excel工作簿07版本
Workbook workbook = new XSSFWorkbook();
//在Excel工作簿中建工作表,即给sheet命名
Sheet sheet = workbook.createSheet("桐哥统计表");
//创建行
Row row1 = sheet.createRow(0);
//创建单元格
Cell cell1 = row1.createCell(0);
cell1.setCellValue("今日收入");
Cell cell2 = row1.createCell(1);
cell2.setCellValue(99999);
Row row2 = sheet.createRow(1);
Cell cell3 = row2.createCell(0);
cell3.setCellValue("统计时间");
Cell cell4 = row2.createCell(1);
String dateTime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
cell4.setCellValue(dateTime);
//新建文件流用来输出
FileOutputStream out = new FileOutputStream(path+"桐哥统计表02.xlsx");
workbook.write(out);
out.close();
System.out.println("文件生成成功");
}
}
POI-Excel写大数据文件
03版本写大文件最多只能处理65536行,否则会抛出异常
虽然行数受限,但一次性可以写完速度快
public class WriteBigDataTest{
@Test
public void testWrite03BigData() throws IOException {
String path = "D:\\excel\\src\\main\\java\\com\\lt\\POIExcel";
//记录开始时间
long begin = System.currentTimeMillis();
//创建一个HSSFWorkbook
Workbook workbook = new HSSFWorkbook();
//创建一个sheet
Sheet sheet = workbook.createSheet();
//xls文件最多执行65536行
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("done");
FileOutputStream out = new FileOutputStream(path+"bigdata03.xls");
workbook.write(out);
// 操作结束,关闭文件
out.close();
//记录结束时间
long end = System.currentTimeMillis();
System.out.println((double)(end - begin)/1000);
}
}
07版本原则上可以写无限,但过程中会产生临时文件(默认100条记录保存在内存,如果超过会写入到临时文件中)
缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万条
@Test
public void testWrite07BigDataFast() throws IOException {
//记录开始时间
long begin = System.currentTimeMillis();
//创建一个SXSSFWorkbook
Workbook workbook = new SXSSFWorkbook();
//创建一个sheet
Sheet sheet = workbook.createSheet();
//xls文件最大支持65536行
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("done");
FileOutputStream out = new FileOutputStream(path+"bigdata07-fast.xlsx");
workbook.write(out);
// 操作结束,关闭文件
out.close();
//清除临时文件
((SXSSFWorkbook)workbook).dispose();
//记录结束时间
long end = System.currentTimeMillis();
System.out.println((double)(end - begin)/1000);
}
未完待续。。。。。