快速掌握POI操作Excel文件的使用

简介:

POI(Apache POI)

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。我们都知道Java是面向对象的思想的一门语言,使用POI不需要想得太过复杂,就是面向对象的思想去创建对象操作Excel文件。

主要使用场景:

  1. 将用户的信息导出为Excel表格;
  2. 将Excel表格的信息录入到网站数据库里,大大减轻网站录入量。

开发中经常会用到对Excel表格的导入和导出,操作Excel目前比较流行的就是 Apache POI 和阿里巴巴的 EasyExcel。

基本功能:

结构:

HSSF - 提供读写[Microsoft Excel](https://baike.baidu.com/item/Microsoft Excel)格式档案的功能。

XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。

HWPF - 提供读写[Microsoft Word](https://baike.baidu.com/item/Microsoft Word)格式档案的功能。

HSLF - 提供读写Microsoft PowerPoint格式档案的功能。

HDGF - 提供读写[Microsoft Visio](https://baike.baidu.com/item/Microsoft Visio)格式档案的功能。

Excel文件分为03版和07版两种,文件后缀分别为 xls 和 xlsx 结尾,所以操作的对象有所不同。HSSF 提供 xls 文件读写,XSSF 提供xlsx文件读写。

操作示例:

导入依赖:

分别导入两种版本 Excel 文件操作的依赖,以及日期格式化工具方便处理日期,测试依赖进行单元测试。

	<dependencies>
		<!--xls(03)-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <!--xls(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>
        <!--test-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

写Excel文件:

1、03版本文件写入
public class Excel03WriteTest {
	// 定义创建的Excel文件存放路径
    String path = "E:\\IdeaProjects\\POI-EasyEel\\";
    
    @Test
    public void testWrite03 (){
        //1、创建一个工作簿,一个Excel文件即为一个工作簿,03创建的是HSSFWorkbook
        Workbook workbook = new HSSFWorkbook();
        //2、创建一个工作表,一个Excel文件可有三张表
        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("创建人");

        //5、创建第二行
        Row row2 = sheet.createRow(1);
        Cell cell3 = row2.createCell(0);
        Cell cell4 = row2.createCell(1);
        String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        cell3.setCellValue(time);
        cell4.setCellValue("admin");

        //生成一张表(流)  03版本就是使用xls结尾
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(path + "03.xls");
            workbook.write(outputStream);
            //关闭流
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

结果如下:
在这里插入图片描述

2、07版本文件写入
public class Excel07WriteTest {
	// 定义创建的Excel文件存放路径
    String path = "E:\\IdeaProjects\\POI-EasyEel\\";

    @Test
    public void testWrite07 (){
        //1、创建一个工作簿,一个Excel文件即为一个工作簿,07创建的是XSSFWorkbook
        Workbook workbook = new XSSFWorkbook();
        //2、创建一个工作表,一个Excel文件可有三张表
        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("创建人");

        //5、创建第二行
        Row row2 = sheet.createRow(1);
        Cell cell3 = row2.createCell(0);
        Cell cell4 = row2.createCell(1);
        String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        cell3.setCellValue(time);
        cell4.setCellValue("admin");

        //生成一张表(流)  07版本就是使用xlsx结尾
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(path + "07.xlsx");
            workbook.write(outputStream);
            //关闭流
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

结果和上一个并没太大区别:
在这里插入图片描述

3、导入大量数据

当导入大量数据时,03版本对象和07版本对象操作数据的时间有所不同,下面探索一下两种方式时间的长短。

  • 03版本大量数据写入
    @Test
    public void testWrite03BigData() throws FileNotFoundException {
            //开始时间
            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 outputStream = new FileOutputStream(path + "03BigData.xls");
            try {
                workbook.write(outputStream);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println((end-begin)/1000);
    }
    

    在这里插入图片描述

  • 07版本大量数据写入

    @Test
    public void testWrite07BigData() throws FileNotFoundException {
            //开始时间
            long begin = System.currentTimeMillis();
            //创建工作簿
            Workbook workbook = new XSSFWorkbook();
            //创建表
            Sheet sheet = workbook.createSheet();
            //写入大量数据
            for (int rowNum = 0; rowNum < 65537; rowNum++) {
                Row row = sheet.createRow(rowNum);
                for (int cellNum = 0; cellNum < 10; cellNum++) {
                    Cell cell = row.createCell(cellNum);
                    cell.setCellValue(cellNum);
                }
            }
            FileOutputStream outputStream = new FileOutputStream(path + "07BigData.xlsx");
            try {
                workbook.write(outputStream);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println((end-begin)/1000);
    }
    

    在这里插入图片描述

    由以上测试结果可以看出,XSSFWorkbook对象的Excel文件导入速度明显慢于HSSFWorkbook对象文件导入,但03版本Excel文件最多只能存储65536行数据,而07版本理论上没有限制。但是HSSFWorkbook非常耗内存,也会发生内存溢出,而POI中有一个对象SXSSFWorkbook使用了缓存机制,写数据快,占用内存更少,写数据量大。

  • SXSSF 大量数据写入

    	@Test
        //07版本  使用缓存提高了速度
        public void testWrite07BigDataS() throws FileNotFoundException {
            //开始时间
            long begin = System.currentTimeMillis();
            //创建工作簿
            Workbook workbook = new SXSSFWorkbook();
            //创建表
            Sheet sheet = workbook.createSheet();
            //写入数据
            for (int rowNum = 0; rowNum < 65537; rowNum++) {
                Row row = sheet.createRow(rowNum);
                for (int cellNum = 0; cellNum < 10; cellNum++) {
                    Cell cell = row.createCell(cellNum);
                    cell.setCellValue(cellNum);
                }
            }
            FileOutputStream outputStream = new FileOutputStream(path + "07BigDataS.xlsx");
            try {
                workbook.write(outputStream);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //由于使用了缓存,生成了临时文件,故需要清除临时文件
            ((SXSSFWorkbook) workbook).dispose();
            
            long end = System.currentTimeMillis();
            System.out.println((end-begin)/1000);
        }
    

    在这里插入图片描述
    可以看到它相较于 XSSF 导入速度有了明显的加快。

读Excel文件:

1、普通读取,读取表中字符串数据
public class ExcelReadTest {
	// 定义读取的Excel文件路径
    String path = "E:\\IdeaProjects\\POI-EasyEel\\03.xls";

    @Test
    public void testRead() throws IOException {
        //获取文件流
        FileInputStream inputStream = new FileInputStream(path);
        //1、创建一个工作簿,使用excel能操作的,它都可以操作!
        //根据文件后缀判断创建xls或xlsx的操作对象
        String file = path.substring(path.lastIndexOf("."));
        if("xls".equals(file)){
            Workbook workbook = new HSSFWorkbook(inputStream); // 03版
        }else{
         	Workbook workbook = new XSSFWorkbook(inputStream); // 07版
        }
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到行
        Row row = sheet.getRow(0);
        //4、得到列
        Cell cell = row.getCell(0);

        System.out.println(cell.getStringCellValue()); //得到表中的字符串内容
        inputStream.close();
    }
2、表中数据类型多样时
	@Test
    public void testCellType() throws IOException {
        //获取文件流
        FileInputStream inputStream = new FileInputStream(path + "03.xls");
        //1、创建一个工作簿,根据文件后缀判断创建xls或xlsx的操作对象
        String file = path.substring(path.lastIndexOf("."));
        if("xls".equals(file)){
            Workbook workbook = new HSSFWorkbook(inputStream); // 03版
        }else{
         	Workbook workbook = new XSSFWorkbook(inputStream); // 07版
        }
        //2、得到表
        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){
                    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 = rowTitle.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 CELL_TYPE_STRING: //字符串
                                System.out.print("【STRING】");
                                cellValue = cell.getStringCellValue();
                                break;
                            case CELL_TYPE_BOOLEAN: //布尔
                                System.out.print("【BOOLEAN】");
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case CELL_TYPE_BLANK: //空
                                System.out.print("【BLANK】");
                                break;
                            case CELL_TYPE_NUMERIC: //数字(日期、普通数字)
                                System.out.print("【NUMRIC】");
                                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(CELL_TYPE_STRING);
                                    cellValue = cell.toString();
                                }
                                break;
                            case CELL_TYPE_ERROR: //错误
                                System.out.print("【数据类型错误】");
                                break;
                        }
                        System.out.print(cellValue); // 最后都转换为String输出
                    }
                }
            }
        }
        inputStream.close();
    }
3、获取表中公式时
	@Test
    //获取公式
    public void testFormula() throws IOException {
        //获取文件流
        FileInputStream inputStream = new FileInputStream(path + "xx.xls");
        //1、创建一个工作簿,根据文件后缀判断创建xls或xlsx的操作对象
        String file = path.substring(path.lastIndexOf("."));
        if("xls".equals(file)){
            Workbook workbook = new HSSFWorkbook(inputStream); // 03版
        }else{
         	Workbook workbook = new XSSFWorkbook(inputStream); // 07版
        }
        //2、得到表
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到行
        Row row = sheet.getRow(0);
        //4、得到列
        Cell cell = row.getCell(0);

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

        //输出单元格的内容
        int cellType = cell.getCellType();
        switch (cellType) {
            case 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;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值