java之使用poi对excel的.xls和.xlsx访问

Excel文档有.xls和.xlsx后缀的,当我们想把它们放在一个方法中进行读取excel文件时,有一个特别省事的做法:

 

 1  public static List<String> Read(String path) throws IOException {
 2 //调用read方法,传入你要读文件的位置,如:c:\new\one.xls
 3 List<String> list = new ArrayList<>();//用来存储读取Excel文件中的数据
 4 FileInputStream in=new FileInputStream(path);
 5         Workbook workbook = null;
 6         //获取工作表
 7         if(path.endsWith(".xlsx")){
 8             workbook=new XSSFWorkbook(in);
 9 
10         }
11         else
12         {
13         workbook=new HSSFWorkbook(in);
14         }
15         Sheet sheet = workbook.getSheetAt(0);
16        int lastRowNum=sheet.getLastRowNum();
17         for (int i = 0; i <= lastRowNum; i++) {
18      
19         Row row = sheet.getRow(i);//获取行(现在拿到每一行
20             if (row != null) {
21                 int lastcellnum = row.getLastCellNum();
22                 for (int j = 0; j < lastcellnum; j++) {//3获取每个单元格
23                     Cell cell = row.getCell(j);
24                     if (cell != null) {
25                         cell.setCellType(Cell.CELL_TYPE_STRING);
26                         String value = cell.getStringCellValue();//读取单元格数据
27                         System.out.println(value);
28                         list.add(value);
29                         }       
30                      }
31                  }
32              }
33 
34       return list;
35 }         

 

posted @ 2020-07-07 08:31  Hey蜗牛  阅读(601)  评论(0编辑  收藏  举报