POI-Excel读写以及easyExcel简单读

本文介绍了使用POI库进行Excel的读写操作,包括POI的大文件写入策略,如HSSF、XSSF和SXSSF的区别及优缺点。对于读操作,提到了03版本和07版本的不同之处。此外,还简述了EasyExcel的使用,强调了其在处理大量数据时的内存效率优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POI-Excel写

导入依赖

<dependencies>
  <!--xlsx(03)-->
  <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
  </dependency>

  <!--xlsx(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>
String path ="C:\\Users\\2020\\IdeaProjects\\SpringFuXi\\poi\\src\\main\\java\\org\\example";
    @Test
    public void testWrite03() throws IOException {
    //1.创建一个工作簿
    Workbook workbook = new HSSFWorkbook();

    //2.创建一个工作表
    Sheet sheet = workbook.createSheet("统计表");

    //3.创建一个行
    Row row1 = sheet.createRow(0);

    //4.创建一个单元格
    Cell cell = row1.createCell(0);
    cell.setCellValue("今日新增");

    Cell cell1 = row1.createCell(1);
    cell1.setCellValue(666);


    //创建第二行
        Row row2 = sheet.createRow(1);

        Cell cell2 = row2.createCell(0);
        cell2.setCellValue("统计时间");
        Cell cell3 = row2.createCell(1);
        cell3.setCellValue(new DateTime().toString("yyyy-MM-dd HH-mm-ss"));


        //生成一张表 03版本就是使用xls结尾
        FileOutputStream fileOutputStream = new FileOutputStream(path + "统计表03.xls");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        System.out.println("生成完毕");
    }






@Test
    public void testWrite07() throws IOException {
        //1.创建一个工作簿
        Workbook workbook = new XSSFWorkbook();

        //2.创建一个工作表
        Sheet sheet = workbook.createSheet("统计表");

        //3.创建一个行
        Row row1 = sheet.createRow(0);

        //4.创建一个单元格
        Cell cell = row1.createCell(0);
        cell.setCellValue("今日新增");

        Cell cell1 = row1.createCell(1);
        cell1.setCellValue(666);


        //创建第二行
        Row row2 = sheet.createRow(1);

        Cell cell2 = row2.createCell(0);
        cell2.setCellValue("统计时间");
        Cell cell3 = row2.createCell(1);
        cell3.setCellValue(new DateTime().toString("yyyy-MM-dd HH-mm-ss"));


        //生成一张表 03版本就是使用xls结尾
        FileOutputStream fileOutputStream = new FileOutputStream(path + "统计表07.xlsx");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        System.out.println("07生成完毕");
    }

注意对象的区别,文件后缀!

03 大文件写HSSF

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

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

@Test
    public void bigData03() throws IOException {
        long begin = System.currentTimeMillis();

        Workbook workbook = new HSSFWorkbook();

        Sheet sheet = workbook.createSheet();
        for (int i = 0; i < 65536; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 10; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(j);
            }
        }
        System.out.println("over");
        FileOutputStream fileOutputStream = new FileOutputStream(path+"大文件写入03.xls");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end-begin)/1000);
    }

07 大文件写XSSF

缺点:写数据速度非常慢,非常耗内存,也会发生内存溢出,如100万条

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

优点:可以写较大的数据量,如20万条

@Test
    public void bigData07() throws IOException {
        long begin = System.currentTimeMillis();

        Workbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet();
        for (int i = 0; i < 65537; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 10; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(j);
            }
        }
        System.out.println("over");
        FileOutputStream fileOutputStream = new FileOutputStream(path+"大文件写入07.xlsx");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end-begin)/1000);
    }

大文件写SXSSF

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

注意:

过程中会产生临时文件,需要清理临时文件.

默认由100条记录被保存在内存中,如果超过这个数量,则最前面的数据被写入临时文件

如果像自定义内存中数据的数量,可以使用new SXSSWorkBook(数量)

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

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

@Test
public void bigData07S() throws IOException {
    long begin = System.currentTimeMillis();

    Workbook workbook = new SXSSFWorkbook();

    Sheet sheet = workbook.createSheet();
    for (int i = 0; i < 65537; i++) {
        Row row = sheet.createRow(i);
        for (int j = 0; j < 10; j++) {
            Cell cell = row.createCell(j);
            cell.setCellValue(j);
        }
    }
    System.out.println("over");
    FileOutputStream fileOutputStream = new FileOutputStream(path+"大文件写入07S.xlsx");
    workbook.write(fileOutputStream);
    fileOutputStream.close();


    //删除临时文件
    ((SXSSFWorkbook)workbook).dispose();

    long end = System.currentTimeMillis();
    System.out.println((double) (end-begin)/1000);
}

POI-excel读

03版本

@Test
public void testRead03() throws IOException {
    //获取文件流
    FileInputStream fis = new FileInputStream(path+"example统计表03.xls");

    //1.创建一个工作簿,使用excel能操作的这边他都可以操作
    Workbook workbook = new HSSFWorkbook(fis);
    //得到表
    Sheet sheetAt = workbook.getSheetAt(0);
    //得到列
    Row row = sheetAt.getRow(1);
    //得到行
    Cell cell = row.getCell(0);

    //读取值的时候一定要注意读取类型
    System.out.println(cell.getStringCellValue());

    fis.close();


}

07版本

@Test
public void testRead07() throws IOException {
    //获取文件流
    FileInputStream fis = new FileInputStream(path+"example统计表07.xlsx");

    //1.创建一个工作簿,使用excel能操作的这边他都可以操作
    Workbook workbook = new XSSFWorkbook(fis);
    //得到表
    Sheet sheetAt = workbook.getSheetAt(0);
    //得到列
    Row row = sheetAt.getRow(0);
    //得到行
    Cell cell = row.getCell(0);

    //读取值的时候一定要注意读取类型
    System.out.println(cell.getStringCellValue());

    fis.close();


}

注意获取值的类型即可

读取不同的数据类型(比较麻烦)

@Test
public void testCellType() throws IOException {
    //获取文件流
    FileInputStream fis = new FileInputStream(path+"example统计表03.xls");

    //1.创建一个工作簿,使用excel能操作的这边他都可以操作
    Workbook workbook = new HSSFWorkbook(fis);

    //获取标题内容
    Sheet sheetAt = workbook.getSheetAt(0);

    //获取标题内容
    Row title = sheetAt.getRow(0);

    if (title!=null){
        int cellCount = title.getPhysicalNumberOfCells();   //获取第一行的元素个数
        for (int i = 0; i < cellCount; i++) {
            Cell cell = title.getCell(i);
            if (cell != null) {
                CellStyle cellType = cell.getCellStyle();
                String stringCellValue = cell.getStringCellValue();
                System.out.print(stringCellValue+"|");


            }
        }
        System.out.println();
    }

    //获取表中内容
    int rowCount = sheetAt.getPhysicalNumberOfRows();
    for (int i = 1; i < rowCount ; i++) {
        Row rowData = sheetAt.getRow(i);
        if (rowData != null) {
            //读取列
            int cellCount = title.getPhysicalNumberOfCells();
            for (int j = 0; j < cellCount; j++) {
                System.out.print("["+(i+1)+"-"+(j+1)+"]");

                Cell cell = rowData.getCell(j);
                //匹配列的数据类型
                if (cell!=null){
                    int cellType = cell.getCellType();
                    String cellValue = "";

                    switch (cellType){
                        case Cell.CELL_TYPE_STRING: //字符串
                            System.out.print("[String]");
                            cellValue = cell.getStringCellValue();
                            break;

                        case Cell.CELL_TYPE_BOOLEAN: //布尔值
                            System.out.print("[Boolean]");
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;

                        case Cell.CELL_TYPE_BLANK: //空白
                            System.out.print("[null]");
                            break;

                        case Cell.CELL_TYPE_NUMERIC: //数字
                            System.out.print("[CELL_TYPE_NUMERIC]");
                            if (HSSFDateUtil.isCellDateFormatted(cell)){    //日期
                                System.out.print("日期");
                                Date date = cell.getDateCellValue();
                                cellValue = new DateTime(date).toString("yyyy-MM-dd");
                            }else {
                                //如果不是日期格式,防止数字过长,
                                System.out.print("普通数字");
                                cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                cellValue = String.valueOf(cell.getNumericCellValue());
                            }
                            break;

                        case Cell.CELL_TYPE_ERROR: //错误
                            System.out.print("[数据类型错误]");
                            break;
                    }
                    System.out.println(cellValue);
                }
            }
        }
    }

    fis.close();

}

计算公式

@Test
    public void testFormula() throws IOException {
        FileInputStream fis = new FileInputStream(path+"example统计表03.xls");

        Workbook workbook = new HSSFWorkbook(fis);

        Sheet sheetAt = workbook.getSheetAt(0);

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

        //拿到计算公司 eval
        FormulaEvaluator hssfFormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);

        //输出单元内容
        int cellType = cell.getCellType();
        switch (cellType){
            case Cell.CELL_TYPE_FORMULA:    //公式
                String cellFormula = cell.getCellFormula();
                System.out.println(cellFormula);

                //计算
                CellValue evaluate = hssfFormulaEvaluator.evaluate(cell);
                String cellValue = evaluate.formatAsString();
                System.out.println(cellValue);
                break;
        }

    }

EasyExcel

1.导入依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>2.2.0-beta2</version>
</dependency>
写入
public void simpleWrite(){
    String path ="C:\\Users\\2020\\IdeaProjects\\SpringFuXi\\poi\\src\\main\\java\\org\\example\\";

    String fileName = path+"EasyTest.xlsx";
    //这里需要指定写用那个class去写,然后写到第一个sheet,名字为模板,然后文件流会自动关闭
    //write(fileName,格式类)
    //sheet(表明)
    //doWrite(数据)
    EasyExcel.write(fileName,DemoData.class).sheet("模板").doWrite(data());


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值