使用POI读取另一行excel文件

时间:2017-05-01 18:48:29

标签: java excel apache-poi

使用Apache POI,我正在尝试读取excel文件。该文件有1000行和1列。使用此代码:

    XSSFSheet ws = workbook.getSheetAt(0);
    Iterator< Row > rowIt = ws.iterator();
    XSSFRow row;
    int i = 0;
    while ( rowIt.hasNext() ) {
      row = (XSSFRow) rowIt.next();
      Iterator< Cell > cellIt = row.cellIterator();
      while ( cellIt.hasNext() ) {
        Cell cell = cellIt.next();
        my_array[ i ] = cell.getStringCellValue();
      }
      ++i;
    }

它似乎读取1001行,因为最后一行是“”,my_array会得到无效的字符串。有没有办法解决这个问题?我希望rowIt.hasNext()对此负责,但它不能按预期工作。

1 个答案:

答案 0 :(得分:1)

  

该文件有1000行和1列:您必须指定要读取的列。   这里是一个用excel文件指定列的例子:

exemple excel file

public class TestLecture {

public static void main(String[] args) throws IOException{

    List<String> mys_list= new ArrayList<String>();
    FileInputStream file = new FileInputStream(new File("test.xlsx"));

    //Get the workbook instance for XLS file 
    XSSFWorkbook workbook = new XSSFWorkbook (file);

    //Get first sheet from the workbook
    XSSFSheet ws = workbook.getSheetAt(0);

    //Get iterator to all the rows in current sheet
    Iterator<Row> rowIt = ws.iterator();


     while (rowIt.hasNext()) {

         Row row = rowIt.next();
         Iterator<Cell> cellIt = row.iterator();

         while (cellIt.hasNext()) {

             Cell cell = cellIt.next();
             int columnIndex = cell.getColumnIndex();
             switch (columnIndex) {
             case 2:

                 mys_list.add(cell.getStringCellValue());

                 break;


             }

         }


     }

     System.out.println(mys_list.size());
     for(String g :mys_list){
         System.out.println(g);
     }



}

}