java,apache poi,nullpoint错误

时间:2014-02-05 11:01:52

标签: java nullpointerexception apache-poi

我有一个看起来像这样的excel文件

Name       Mark
CHE102     80
MTE100     85
MATH115 
.
.
.
.
.
..

我使用此代码此方法来提取信息

public void readData(Row row,Sheet ws){
    Iterator<Cell> cellIterator = row.cellIterator();
    Cell cell=cellIterator.next();
    name=cell.getStringCellValue();
    cell=cellIterator.next();
    mark=cell.getNumericCellValue();
}   

在我的主要使用for循环的im中如下:

for(int i=0;i<5;i++){
            arr[i]=new Test();
            Row row=rowIterator.next();
            arr[i].readData(row,ws);
             arr[i].setGrade();
             arr[i].outputData();
        }

但问题是,因为我的excel文件中有很多空单元格,所以我得到了一个nullpoint错误 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

你应该通过明确检查它们来防范nullvalise:

例如,你可以写

name= (cell==null) ? "" : cell.getStringCellValue();

但是,cellIterator只返回非空单元格,因此当'name'为空时会得到奇怪的结果。

而是尝试:

public void readData(Row row,Sheet ws){
    Cell cell=row.getCell(0, Row.RETURN_BLANK_AS_NULL);
    name= (cell==null) ? "" : cell.getStringCellValue();
    cell=row.getCell(1, Row.RETURN_BLANK_AS_NULL);
    mark= (cell==null) ? 0 : cell.getNumericCellValue();
}   

显式处理两个单元格。当然,您可以使用不同的逻辑而不是使用空字符串,使用0表示不存在的单元格。

另见:http://poi.apache.org/spreadsheet/quick-guide.html#Iterator

答案 1 :(得分:0)

尝试以下代码。根据您的要求进行更改。

Row r = sheet.getRow(myRowNum);
int lastColumn = r.getLastCellNum();

for (int cn=0; cn<lastColumn; cn++) {
   Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
   if (c == null) {
      // The spreadsheet is empty in this cell
   } else {
      // Do something useful with the cell's contents
   }
}

答案 2 :(得分:0)

我发现问题出现在“标记”列中 - 单元格为空,然后cell.getNumericCellValue抛出错误:尝试使用try ... catch

这样的事情:

try {
   mark = cell.getNumericCellValue();
} catch (Exception exc) {
   mark = null;
}

此外,如果事先不知道行计数,则应编写迭代器终止逻辑,在示例中,您只是循环到5。