我想养只狗

博客园 首页 联系 订阅 管理

POI 和 easyExcel 笔记

常用信息

  1. 将用户信息导出为Excel表格(导出数据...)

  2. 将Excel表中的信息录入到网站数据库

    操作Excel目前比较流行的就是Apache POI 和 阿里巴巴的EasyExcel

POI-Excel写

创建项目

1、创建一个空项目

2、引入pom依赖

<dependencies>
        <!-- POI Excel 03 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <!-- POI Excel 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>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

03|07

03版本

@Test
    public void testWrite03() throws Exception {
        //1.创建一个工作簿03
        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(666);

        Row row2 = sheet.createRow(1);
        //4.创建一个单元格
        Cell cell3 = row2.createCell(0);
        cell3.setCellValue("统计时间");

        Cell cell4 = row2.createCell(1);
        String createtime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        cell4.setCellValue(createtime);

        //生成表
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "观众统计表03.xls");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("创建excel03结束");
    }

07版本

@Test
    public void testWrite07() throws Exception {
        //1.创建一个工作簿07
        Workbook workbook = new XSSFWorkbook();
        //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(666);

        Row row2 = sheet.createRow(1);
        //4.创建一个单元格
        Cell cell3 = row2.createCell(0);
        cell3.setCellValue("统计时间");

        Cell cell4 = row2.createCell(1);
        String createtime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        cell4.setCellValue(createtime);

        //生成表
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "观众统计表07.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("创建excel07结束");
    }

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

大文件写HSSF

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

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

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

@Test
    public void testWrite03BigData() throws Exception {
        //开始时间
        long begin = System.currentTimeMillis();
        //1.创建一个工作簿03
        Workbook workbook = new HSSFWorkbook();
        //2.创建一个工作表
        Sheet sheet = workbook.createSheet();
        //写入数据
        for (int rowNum = 0; rowNum < 65536; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for(int cellNum = 0; cellNum < 10; cellNum++) {
                Cell cell1 = row.createCell(cellNum);
                cell1.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        //生成表
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWrite03BigData.xls");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end - begin)/1000);

    }

大文件写XSSF

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

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

//耗时长
    @Test
    public void testWrite07BigData() throws Exception {
        //开始时间
        long begin = System.currentTimeMillis();
        //1.创建一个工作簿03
        Workbook workbook = new XSSFWorkbook();
        //2.创建一个工作表
        Sheet sheet = workbook.createSheet();
        //写入数据
        for (int rowNum = 0; rowNum < 65536; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for(int cellNum = 0; cellNum < 10; cellNum++) {
                Cell cell1 = row.createCell(cellNum);
                cell1.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        //生成表
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWrite07BigData.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        long end = System.currentTimeMillis();
        System.out.println((double) (end - begin)/1000);

    }

大文件写SXSSF

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

注意:

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

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

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

//升级版
    @Test
    public void testWrite07BigDataS() throws Exception {
        //开始时间
        long begin = System.currentTimeMillis();
        //1.创建一个工作簿03
        Workbook workbook = new SXSSFWorkbook();
        //2.创建一个工作表
        Sheet sheet = workbook.createSheet();
        //写入数据
        for (int rowNum = 0; rowNum < 65536; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for(int cellNum = 0; cellNum < 10; cellNum++) {
                Cell cell1 = row.createCell(cellNum);
                cell1.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        //生成表
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "testWrite07BigDataS.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        //清除临时文件
        ((SXSSFWorkbook) workbook).dispose();
        long end = System.currentTimeMillis();
        System.out.println((double) (end - begin)/1000);

    }

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

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

POI-Excel读

03|07

03版本

@Test
    public void testRead03() throws Exception {
        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(PATH + "观众统计表03.xls");
        //1.创建一个工作簿03,使用Excel能操作的这边都能操作!
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到行
        Row row = sheet.getRow(0);
        //4、得到列
        Cell cell = row.getCell(0);

        //读取值得时候,一定要注意类型!
        System.out.println(cell.getStringCellValue());
        fileInputStream.close();
    }

07版本

@Test
    public void testRead07() throws Exception {
        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(PATH + "观众统计表07.xlsx");
        //1.创建一个工作簿03,使用Excel能操作的这边都能操作!
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到行
        Row row = sheet.getRow(0);
        //4、得到列
        Cell cell = row.getCell(0);

        //读取值得时候,一定要注意类型!
        System.out.println(cell.getStringCellValue());
        fileInputStream.close();
    }

注意获取值的类型

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

@Test
    public void testCellType() throws Exception {
        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(PATH + "观众统计表07.xls");
        //1.创建一个工作簿03,使用Excel能操作的这边都能操作!
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //读取表头
        Row row1 = sheet.getRow(0);
        if(row1 != null) {
            int celCount = row1.getPhysicalNumberOfCells();
            for(int cellNum = 0; cellNum < celCount; cellNum++) {
                Cell cell = row1.getCell(cellNum);
                if(cell != null) {
                    int 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 = row1.getPhysicalNumberOfCells();
                for (int cellNum = 0; cellNum < cellCount; cellNum++) {
                    System.out.print("["+(rowNum+1)+"-"+(cellNum+1)+"]");

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

                        switch (cellType) {
                            case HSSFCell.CELL_TYPE_STRING:
                                System.out.print("【String】");
                                cellValue = cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                System.out.print("【Boolean】");
                                cellValue = String.valueOf(cell.getStringCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                System.out.print("【NUMERIC】");
                                if(HSSFDateUtil.isCellDateFormatted(cell)) {//日期
                                    System.out.print("【Date】");
                                    Date date = cell.getDateCellValue();
                                    cellValue = new DateTime(date).toString("yyyy-MM-dd");
                                } else {
                                    //不是日期格式,防止数字过长!
                                    System.out.print("【转换为字符串输出】");
                                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                    cellValue = cell.toString();
                                }
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                System.out.print("【数据类型错误】");
                                break;
                        }
                        System.out.println(cellValue);
                    }
                }
            }
        }

        fileInputStream.close();
    }

注意,类型转换问题

计算公式

@Test
    public void testFormula() throws Exception {
        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(PATH + "公式.xls");
        //1.创建一个工作簿03,使用Excel能操作的这边都能操作!
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到公式行
        Row row = sheet.getRow(4);
        //4、得到公式列
        Cell cell = row.getCell(0);

        //拿到计算公式
        FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);

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

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

        fileInputStream.close();
    }

EasyExcel操作

导入依赖

<!--easyExcel-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.0-beta3</version>
        </dependency>

写入测试

https://alibaba-easyexcel.github.io/index.html

读取测试

https://alibaba-easyexcel.github.io/index.html

固定套路:

1、写入,固定类格式进行写入

2、读取,根据监听器设置的规则进行读写!

posted on 2021-10-12 18:32  我想养只狗  阅读(208)  评论(0)    收藏  举报