2014-02-05 27 views
0

我有看这个样子的的java,Apache的POI,nullpoint错误

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(); 
} 

我主要的IM Excel文件for循环如下:

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文件即时获取零点错误 我该如何解决这个问题?

回答

0

我看到的问题是在“标记”列 - 在细胞是空的,则cell.getNumericCellValue抛出错误:尝试使用try ... catch

事情是这样的:

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

而且,如果行数不是事先知道的,您应该编写迭代器终止逻辑,在这个例子中,您只是循环到5.

+0

谢谢工作完美。 对不起,但我是一个noob在编程中,什么是迭代器终止逻辑 – Anish6595

+0

我的意思是“终止逻辑”:不知何故,你曾预测行数总是5('for(int i = 0; i <5; i ++)' )。没关系,如果是这样的话,但在很多情况下,你不知道确切的行数 - 在这种情况下,你应该以某种方式终止循环。例如,你可以这样检查:如果“Name”单元格值为null,则退出。 – RustamIS

+0

亚得到它感谢:) – Anish6595

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 
    } 
} 
1

您应该gua针对nullvalues RD由他们明确地检查:

例如,你可以写

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

然而,cellIterator只返回非空白单元格,所以你会得到奇怪的结果时,“名称”为空。

而是尝试:

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