java POI读取Excel文件

POI和jxl都能操作Excel,在一开始我选择了jxl来读取Excel文件内容,但在输出读取内容的时候会报错,总结下来就是:

  • jxl只能读取xlsx格式的文件。
  • jxl只能操作2003Excel表格,2007以后的版本则是不可用。

以上两点只是我个人遇到的问题,最后也是没有解决,所有我是采取了用POI来操作Excel。

1.导入maven依赖:

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

2.读取Excel文件内容

 

 public static List<Area> poi1(){
        List<Area> list=new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream("F:\\f\\test1.xlsx");
//            String city;
            Area area=null;
            XSSFWorkbook workbook =  new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
            int firstRowNum = sheet.getFirstRowNum();
            int lastRowNum = sheet.getLastRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            int firstCellNum = firstRow.getFirstCellNum();
            int lastCellNum = firstRow.getLastCellNum();
            System.out.println("第一行行号:" + firstRowNum);
            System.out.println("最后一行行号:" + lastRowNum);
            System.out.println("第一列列号:" + firstCellNum);
            System.out.println("最后一列列号:" + lastCellNum);

       //我这里是指定了行来获取,如果是获取全部单元格内容的话再加一层for循环即可。
for(int i = 0; i < lastCellNum; i++) { //System.out.print(sheet.getRow(2).getCell(i).getNumericCellValue() + " "); String city=sheet.getRow(2).getCell(i).getStringCellValue(); String info=sheet.getRow(1).getCell(i).getStringCellValue(); String user=sheet.getRow(0).getCell(i).getStringCellValue(); String type; if (info.equals("")){ type="varchar(10)"; }else type="int"; // //System.out.println(city); area=new Area(city,user,info,type); list.add(area); //System.out.println(list.get(i)); // list.add(sheet.getRow(2).getCell(i).getStringCellValue()); //System.out.println(sheet.getRow(2).getCell(i).getStringCellValue()+" "); //System.out.println("\n"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; }
posted @ 2021-11-09 19:14  天岁  阅读(661)  评论(0编辑  收藏  举报