Apache POI解析Excel文件(xls)

本文详细介绍了如何在SpringBoot项目中使用ApachePOI库解析Excel文件,包括添加依赖、构建Excel类、测试方法GetExcelDate,以及处理不同类型的单元格内容。

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

目录

一、POI:

二、使用方法:

        1、构建SpringBoot工程,在pom.xml文件中添加依赖:

        2、构建Excel类

        3、构建测试方法GetExcelDate():

                ①获取文件流,构建工作簿(WorkBook):

                ②构建工作页(Sheet):

                ③获取第一行(一般为这一列的标题,所以单独获取出来):

                ④若第一行不为空:获取列数,依次输出:

                ⑤获取这一工作页的有效列数:

                ⑥同上述一样遍历输出对应的值,但是首先提出一个类型判断。由于不能明确对应的值,所以需要进行类型判断,使用switch case语句:

三、代码封装

四、xlsx文件:

五、Apache POI文档:


一、POI:

        POI属于Apache下的一款简易解析Excel的库。可用于解析Excel类的xls、xlsx文件,还支持对Vision的解析。

二、使用方法:

        1、构建SpringBoot工程,在pom.xml文件中添加依赖:
<!--        主要的poi依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

<!--        用于解析xlsx的poi依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.5</version>
        </dependency>

<!--        方便操作日期和时间的库-->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.12.5</version>
        </dependency>

<!--        便于测试的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        2、构建Excel类
        3、构建测试方法GetExcelDate():
public static void GetExcelData() throws IOException
                ①获取文件流,构建工作簿(WorkBook):
        String url = "";  //文件地址
        FileInputStream inputStream = new FileInputStream(url);
        Workbook wb = new HSSFWorkbook(inputStream);
                ②构建工作页(Sheet):
        Sheet sheet = wb.getSheetAt(0);
                ③获取第一行(一般为这一列的标题,所以单独获取出来):
        Row rowTitle = sheet.getRow(0);
                ④若第一行不为空:获取列数,依次输出:
        if(rowTitle != null) {

            //获取这一行有值的有多少列
            int cellNum = rowTitle.getPhysicalNumberOfCells();
            //输出有效列数
            System.out.println(cellNum);

            //遍历有效列数
            for (int cells = 0; cells < cellNum; cells++){

                //获取第一行(rowTitle)对应列数(Cells)的值
                Cell cell = rowTitle.getCell(cells);

                //如果值不为空
                if(cell != null){

                    //获取值对应的类型(标题一般就是字符型可以不要,单纯给出这个API)
                    int cellType = cell.getCellType();

                    //转化为字符串输出
                    String cellvalue = cell.getStringCellValue();
                    System.out.print(cellvalue + '|');
                }
            }
            System.out.println();
        }
                ⑤获取这一工作页的有效列数:
    int rowNum = sheet.getPhysicalNumberOfRows();
                ⑥同上述一样遍历输出对应的值,但是首先提出一个类型判断。由于不能明确对应的值,所以需要进行类型判断,使用switch case语句:

                定义CellType为值所对应的类型,上面给出了提取类型的api:

           switch (cellType) {


                     //String类型
                 case Cell.CELL_TYPE_STRING:
                     String stringCellValue = cell.getStringCellValue();
                     cellValue = stringCellValue;
                     break;

                     //bool类型 
                 case Cell.CELL_TYPE_BOOLEAN:
                     boolean booleanCellValue = cell.getBooleanCellValue();
                      cellValue = String.valueOf(booleanCellValue);
                      break;

                      //空类型
                 case Cell.CELL_TYPE_BLANK:
                      break;

                      //数字或者日期类型
                 case Cell.CELL_TYPE_NUMERIC:

                     // 判断是否是日期
                     if (DateUtil.isCellDateFormatted(cell)) {
                         Date dateCellValue = cell.getDateCellValue();
                         cellValue = new DateTime(dateCellValue).toString("yyyy-MM-dd");
                     }else {

                         // 是数字的转换成字符串获取,防止数字过长
                         // 重新设置单元格的数据类型
                         cell.setCellType(Cell.CELL_TYPE_STRING);
                         cellValue = cell.toString();
                     }
                     break;

                // 类型错误
                 case Cell.CELL_TYPE_ERROR:
                      break;
               }

        以上可能在高版本POI中需要使用:

                 if(cell!=null){
                        CellType cellType = cell.getCellType();
                        switch (cellType){
                            case STRING: System.out.println("String类型");
                            case _NONE: System.out.println("_NONE类型");
                            case NUMERIC: System.out.println("NUMERIC类型");
                            case FORMULA: System.out.println("FORMULA类型");
                            case BLANK: System.out.println("BLANK类型");
                        }
                    }

        大家根据自己的版本选择。

        我们只需要在读取每个单元格的内容时加上上述判断代码就可以了:

for (int rows = 1; rows < rowNum;rows++){
            Row rowData = sheet.getRow(rows);
            if(rowData != null){
                int cellCount = rowTitle.getPhysicalNumberOfCells();
                for(int cellNum = 0;cellNum < cellCount;cellNum++){
                    Cell cell = rowData.getCell(cellNum);
                    if(cell != null){
                        int cellType = cell.getCellType();
                        String cellValue = "";
                        switch (cellType) {
                            case Cell.CELL_TYPE_STRING:
                                String stringCellValue = cell.getStringCellValue();
                                cellValue = stringCellValue;
                                break;
                            case Cell.CELL_TYPE_BOOLEAN:
                                boolean booleanCellValue = cell.getBooleanCellValue();
                                cellValue = String.valueOf(booleanCellValue);
                                break;
                            case Cell.CELL_TYPE_BLANK:
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    Date dateCellValue = cell.getDateCellValue();
                                    cellValue = new DateTime(dateCellValue).toString("yyyy-MM-dd");
                                }else {
                                    cell.setCellType(Cell.CELL_TYPE_STRING);
                                    cellValue = cell.toString();
                                }
                                break;
                            case Cell.CELL_TYPE_ERROR:
                                break;
                        }
                        System.out.print(cellValue + '|');
                    }
                }
            }
            System.out.println();
        }

        对应的原理与读取标题行的一致。

三、代码封装

               我们只需要将数据流的获取放在函数参数体中就行了。具体完整代码如下:

package com.example.contoller;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.joda.time.DateTime;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

public  class Excel {
    @Test
    public static void GetExcelData(FileInputStream inputStream) throws IOException {
        Workbook wb = new XSSFWorkbook(inputStream);

        Sheet sheet = wb.getSheetAt(0);
        Row rowTitle = sheet.getRow(0);

        if(rowTitle != null) {
            int cellNum = rowTitle.getPhysicalNumberOfCells();
            System.out.println(cellNum);
            for (int cells = 0; cells < cellNum; cells++){
                Cell cell = rowTitle.getCell(cells);
                if(cell != null){
                    int cellType = cell.getCellType();
                    String cellvalue = cell.getStringCellValue();
                    System.out.print(cellvalue + '|');
                }
            }
            System.out.println();
        }
        int rowNum = sheet.getPhysicalNumberOfRows();
        for (int rows = 1; rows < rowNum;rows++){
            Row rowData = sheet.getRow(rows);
            if(rowData != null){
                int cellCount = rowTitle.getPhysicalNumberOfCells();
                for(int cellNum = 0;cellNum < cellCount;cellNum++){
                    Cell cell = rowData.getCell(cellNum);
                    if(cell != null){
                        int cellType = cell.getCellType();
                        String cellValue = "";

                        switch (cellType) {
                            case Cell.CELL_TYPE_STRING:
                                String stringCellValue = cell.getStringCellValue();
                                cellValue = stringCellValue;
                                break;
                            case Cell.CELL_TYPE_BOOLEAN:
                                boolean booleanCellValue = cell.getBooleanCellValue();
                                cellValue = String.valueOf(booleanCellValue);
                                break;
                            case Cell.CELL_TYPE_BLANK:
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    Date dateCellValue = cell.getDateCellValue();
                                    cellValue = new DateTime(dateCellValue).toString("yyyy-MM-dd");
                                }else {
                                    cell.setCellType(Cell.CELL_TYPE_STRING);
                                    cellValue = cell.toString();
                                }
                                break;
                            case Cell.CELL_TYPE_ERROR:
                                break;
                        }
                        System.out.print(cellValue + '|');
                    }
                }
            }
            System.out.println();
        }
    }

}

四、xlsx文件:

        对于该07Excel的解析,我们只需要导入的文件换成xlsx,工作簿的创建步骤中将HSSFWorkbook换成XSSFWorkbook就行了。

五、Apache POI文档:

https://poi.apache.org/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值