POI&easyExcel

03
//创建工作蒲
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet(projectName + "面试成绩汇总表");

//设置列宽
for (int i = 0; i <5; i++) {
sheet.setColumnWidth(i, 4000);
}
sheet.setColumnWidth(1, 9000);
sheet.setColumnWidth(2, 9000);
sheet.setColumnWidth(3, 9000);
sheet.setColumnWidth(4, 9000);
// 设置字体
   HSSFFont headfont = workbook.createFont();
   headfont.setFontName("宋体");
   // 字体大小
   headfont.setFontHeightInPoints((short) 12);
   // 加粗
   headfont.setBold(true);
//设置样式(头部)
HSSFCellStyle headStyle = workbook.createCellStyle();
headStyle.setFont(headfont);
// 左右居中
   headStyle.setAlignment(CENTER);
   // 上下居中
headStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
//是否锁定单元格
headStyle.setLocked(true);
   // 自动换行
   headStyle.setWrapText(true);
//边框
//               twoStyle.setTopBorderColor(HSSFColor.BLACK.index);
           headStyle.setBorderTop(THIN);
//               twoStyle.setLeftBorderColor(HSSFColor.BLACK.index);
           headStyle.setBorderLeft(THIN);
//               twoStyle.setRightBorderColor(HSSFColor.BLACK.index);
           headStyle.setBorderRight(THIN);
//               twoStyle.setBottomBorderColor(HSSFColor.BLACK.index);
           headStyle.setBorderBottom(THIN);
//背景颜色
headStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
   headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

//设置单元格百分比样式
HSSFCellStyle cellStyleRatio = workbook.createCellStyle();
cellStyleRatio.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
//设置单元格货币样式
HSSFCellStyle cellMoneyStyle = workbook.createCellStyle();
HSSFDataFormat format= workbook.createDataFormat();
cellMoneyStyle.setDataFormat(format.getFormat("#,##0"));
//设置单元格小数格式
HSSFCellStyle cellFlotStyle = workbook.createCellStyle();
cellFlotStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));

//创建行(第一行)
org.apache.poi.ss.usermodel.Row row1 = sheet.createRow(0);
//设置行高(第一行标题需要)
row1.setHeight((short) 500);
//创建单元格
org.apache.poi.ss.usermodel.Cell cell11 = row1.createCell(0);
cell11.setCellValue(new HSSFRichTextString("面试成绩汇总表"));
cell11.setCellStyle(headstyle);
//再创四个单元格
for (int i = 1; i < 5; i++) {
               org.apache.poi.ss.usermodel.Cell cell = row1.createCell(i);
               cell.setCellStyle(headstyle);
          }
//合并单元格
CellRangeAddress range = new CellRangeAddress(0, 0, 0, 4);//第一行开始,第一行结束,第一个单元格开始,第五个但单元格结束
sheet.addMergedRegion(range);

// 生成表,IO流,03版本使用xls后缀
FileOutputStream fileOutputStream = new FileOutputStream(zipPath + "/面试成绩汇总表.xls");
//输出
workbook.write(fileOutputStream);
// 关闭流
fileOutputStream.close();

 

POI-Excel写

Apache POI

简介 Apache POI官网: https://poi.apache.org/

HSSF 对应 Excel 03 版本,最多支持65535行

XSSF对应 Excel 07 版本,行数无限制

缺点:

使用比较麻烦 数据量大的时候会可能报OOM异常

创建项目

创建一个空项目,创建两个普通Maven模块

引入pom依赖

<dependencies>

<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>4.1.2version>
dependency>

<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.1.1version>
dependency>

<dependency>
<groupId>joda-timegroupId>
<artifactId>joda-timeartifactId>
<version>2.10.1version>
dependency>

<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>

创建两个版本的Excel文件

打开可以看到,03版最多支持到65536行,而07版不受限制,理论上无限

二者文件名后缀不同,对应操作的Java工具类也不同

03:文件后缀名xls

07:文件后缀名xlsx

相关对象

明确几个概念,工作簿、工作表、行、单元格,分别对应了各自的对象

image-20210805135606769

1.工作蒲:

03(.xls):Workbook workbook = new HSSFWorkbook();

07(.xlsx):Workbook workbook = new XSSFWorkbook();

2.工作表:

Sheet sheet = workbook.createSheet("考核成绩表");

3.行:

Row row1 = sheet.createRow(0);// 第一行

4.单元格:

Cell cell1 = row1.createCell(0);// 第一行的第一列

示例

package com.cz;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.junit.Test;

import java.io.FileOutputStream;

public class ExcelWriteTest {
   // 构建路径
   String PATH = "D:\\java\\javacode\\excel\\cz-poi";

   @Test
   public void testWrite03() throws Exception {
       // 1.创建工作簿
       Workbook workbook = new HSSFWorkbook();
       // 2.创建工作表
       Sheet sheet = workbook.createSheet("考核成绩表");
       // 3.创建第一行
       Row row1 = sheet.createRow(0);// 第一行
       // 4.创建单元格
       Cell cell1 = row1.createCell(0);// 第一行的第一列
       cell1.setCellValue("数学");
       Cell cell2 = row1.createCell(1);// 第一行的第二列
       cell2.setCellValue(100);
       // 第二行
       Row row2 = sheet.createRow(1);// 第二行
       Cell cell21 = row2.createCell(0);// 第二行的第一列
       cell21.setCellValue("时间");
       Cell cell22 = row2.createCell(1);// 二行二列
       cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
       // 生成表,IO流,03版本使用xls后缀
       FileOutputStream fileOutputStream = new FileOutputStream(PATH + "考核成绩表03.xls");
       //输出
       workbook.write(fileOutputStream);
       // 关闭流
       fileOutputStream.close();
       System.out.println("考核成绩表03输出完毕");
  }


   @Test
   public void testWrite07() throws Exception {
       // 创建工作簿
       Workbook workbook = new XSSFWorkbook();
       // 创建工作表
       Sheet sheet = workbook.createSheet("考核成绩表");
       // 创建第一行
       Row row1 = sheet.createRow(0);// 第一行
       // 创建单元格
       Cell cell1 = row1.createCell(0);// 第一行的第一列
       cell1.setCellValue("语文");
       Cell cell2 = row1.createCell(1);
       cell2.setCellValue(100);
       // 第二行
       Row row2 = sheet.createRow(1);// 第一行
       Cell cell21 = row2.createCell(0);// 第一行的第一列
       cell21.setCellValue("时间");
       Cell cell22 = row2.createCell(1);
       cell22.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
       // 生成表,IO流,07版本使用xlsx后缀
       FileOutputStream fileOutputStream = new FileOutputStream(PATH + "考核成绩表07.xlsx");
       workbook.write(fileOutputStream);
       // 关闭流
       fileOutputStream.close();
       System.out.println("考核成绩表07输出完毕");
  }
}

注意03和07对象、文件后缀的区别

 

大文件写HSSF-03

缺点:最多只能处理65536行,否则会报异常

java.lang.IllegalArgumentException:Invalid row number (65536) outside allowable range (0.. 65535)

优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快

@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);
}
}
FileOutputStream fos = new FileOutputStream(PATH + "03版本Excel大量数据测试.xls");
workbook.write(fos);
fos.close();
System.out.println("over");
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
}

大文件写XSSF-07

缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万条数据 优点:可以写较大的数据量,如20万条数据

(修改工作蒲对象,文件后缀名)

@Test
public void testwrite03BigData() throws IOException {
//时间
long begin = System.currentTimeMillis();
//创建一个薄
Workbook workbook = new XSSFWorkbook();
//创建表
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);
}
}
FileOutputStream fos = new FileOutputStream(PATH + "07版本Excel大量数据测试.xlsx");
workbook.write(fos);
fos.close();
System.out.println("over");
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
}

时间较长,但是可以写更多数据

大文件写SXSSF-07升级版

优点:可以写非常大量的数据库,如100万条甚至更多条,写数据速度快,占用更少的内存

注意:

过程中会产生临时文件,需要在程序运行结束后清理临时文件 默认由100条记录被保存在内存中,如果超出这数量,则最前面的数据被写入临时文件 如果想自定义内存中数据的数量,可以使用new SXSSFWorkbook(数量)

Workbook workbook = new SXSSFWorkbook();
Fileoutputstream ops = new Fileoutputstream(PATH +"07版本Excel大量数据测试.xlsx");

@Test
public void testwrite07_S_BigData() throws IOException {
//时间
long begin = System.currentTimeMillis();
//创建一个薄
Workbook workbook = new SXSSFWorkbook(100);
//创建表
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);
}
}
FileOutputStream fos = new FileOutputStream(PATH + "07_S_版本Excel大量数据测试.xlsx");
workbook.write(fos);
fos.close();
//清除临时文件
((SXSSFWorkbook)workbook).dispose();
System.out.println("over");
long end = System.currentTimeMillis();
System.out.println((double) (end - begin) / 1000);
}

SXSSWorkbook 来自官方解释:实现:BigGridDemo策略的流式XSSFWorkbook版本。这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。

请注意:仍然可能会消耗大量内存,这些内存基于您正在使用的功能,如合并区域,注释...仍然只存储在内存中,因此如果广泛使用,可能需要大量内存。

在使用POI时,内存问题可以使用Jprofile监控!

POI-Excel读

03

@Test
public void testRead03() throws Exception {
//获取文件流
FileInputStream fis = new FileInputStream(PATH + "03版本测试.xls");
//1、创建一个工作簿。使用 exceL能操作的这边他都可以操作!
Workbook workbook = new HSSFWorkbook(fis);
//2、得到表
Sheet sheet = workbook.getSheetAt(0);
//3、得到行
Row row = sheet.getRow(0);
//4、得到列
Cell cell = row.getCell(1);

//读取值的时候,一定要注意类型!
//getStringCellValue 字符串类型
System.out.println(cell.getNumericCellValue());
fis.close();
}

07

@Test
public void testRead07() throws Exception {
//获取文件流
FileInputStream fis = new FileInputStream(PATH + "07版本测试.xlsx");
//1、创建一个工作簿。使用 exceL能操作的这边他都可以操作!
Workbook workbook = new XSSFWorkbook(fis);
//2、得到表
Sheet sheet = workbook.getSheetAt(0);
//3、得到行
Row row = sheet.getRow(0);
//4、得到列
Cell cell = row.getCell(0);

//读取值的时候,一定要注意类型!
//getStringCellValue 字符串类型
System.out.println(cell.getStringCellValue());
fis.close();
}

注意获取值的类型即可

读取不同的数据类型,是工作上的重点,这段类型匹配代码工作时直接复制

判断不同的数据类型

@Test
   public void testCellType() throws Exception {

       //获取文件流
       FileInputStream fis = new FileInputStream(PATH + "明细表.xls");

       //创建一个工作簿。使用excel能操作的这边他都可以操作
       Workbook workbook = new HSSFWorkbook(fis);
       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 cellCount = rowTitle.getPhysicalNumberOfCells();
               for (int cellNum = 0; cellNum < cellCount; cellNum++) {
                   System.out.println("[" + (rowNum + 1) + "-" + (cellNum + 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 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("--【转换为字符串输出】");
                                   cellValue = cell.toString();
                              }
                               break;
                           case ERROR://错误
                               System.out.print("【 数据类型错误】");
                               break;
                      }
                       System.out.println(cellValue);
                  }
              }
          }
      }
       //关闭流
       fis.close();
  }

计算公式

//公式
   @Test
   public void testFormula() throws Exception {
       FileInputStream fis = new FileInputStream(PATH+"公式.xls");
       //创建一个工作簿。使用 excel能操作的这边他都可以操作
       Workbook workbook = new HSSFWorkbook(fis);
       Sheet sheet = workbook.getSheetAt(0);

       Row row = sheet.getRow(4);
       Cell cell = row.getCell(0);

       //拿到计算公司 evaL
       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官网地址: https://github.com/alibaba/easyexcel

EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单,节约内存著称。

EasyExcel能大量减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从一个磁盘上一行行读取数据,逐个解析。

 

官方文档: https://www.yuque.com/easyexcel/doc/easyexcel

导入依赖


<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version >2.2.0-beta2version>
dependency>

 

posted @ 2021-09-08 11:42  da-chun  阅读(155)  评论(0)    收藏  举报