POI之导入Excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40369944/article/details/84726217

注:请根据实际的开发情况更改方法

1.导入依赖

<!--poi-->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.6</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
    </dependency>

      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-scratchpad</artifactId>
          <version>3.17</version>
      </dependency>

2.工具类方法(请根据实际应用更改

    /**
     *
     * @param filePath:文件地址(D:/123.xls)
     * @param column:表格列数
     */
    public static void getDataFromExcel(String filePath,int  column) {

        //判断是否为excel类型文件
        if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx")) {
            System.out.println("文件不是excel类型");
        }

        FileInputStream fis =null;
        Workbook wookbook = null;

        try {
            //获取一个绝对地址的流
            fis = new FileInputStream(filePath);
        } catch(Exception e) {
            e.printStackTrace();
        }

        try {
            //2003版本的excel,用.xls结尾
            wookbook = new HSSFWorkbook(fis);//得到工作簿
        } catch (Exception ex) {
            //ex.printStackTrace();
            try {
                //2007版本的excel,用.xlsx结尾

                wookbook = new XSSFWorkbook(fis);//得到工作簿
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //得到一个工作表
        Sheet sheet = wookbook.getSheetAt(0);

        //获得表头
        Row rowHead = sheet.getRow(0);

        //判断表头是否正确
        if(rowHead.getPhysicalNumberOfCells() != column) {
            System.out.println("表头的数量不对!");
        }

        //获得数据的总行数
        int totalRowNum = sheet.getLastRowNum();

        //要获得属性
        String on="";
        String name = "";
        String age = "";

        //获得所有数据
        for(int i = 1 ; i <= totalRowNum ; i++)
        {
            //获得第i行对象
            Row row = sheet.getRow(i);

            //获得获得第i行第0列
            Cell cell = row.getCell((short)0);
            on =  cell.getStringCellValue();

            //获得获得第i行第1列
            cell = row.getCell((short)1);
            name =  cell.getStringCellValue();

            //获得获得第i行第2列
            cell = row.getCell((short)2);
            age =   cell.getStringCellValue();
            System.out.println("编号:"+on+",名字:"+name+",年龄:"+age);

        }
    }

3.测试

@Test
    public void t1(){
        getDataFromExcel("D:\\下载\\人员档案列表.xls",3);
    }

表格内容:

结果如下:

猜你喜欢

转载自blog.csdn.net/qq_40369944/article/details/84726217