试图解析Excel文件

时间:2012-12-21 13:52:37

标签: java apache-poi

我正在尝试以这样的方式解析excel文件:当我找到一个空单元格时,我添加了string的值。示例代码:

for (int e = 0; e < wb.getNumberOfSheets(); e++) {
    sheet = wb.getSheetAt(e);
    for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i++) {
        System.out.println(sheet.getSheetName());
        row = sheet.getRow(i);
        if(row != null) {
            cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
            if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                cell = row.createCell(i);
                cell.setCellValue("foo");
            }
            cell = row.getCell(1, Row.RETURN_BLANK_AS_NULL);
            if(cell == null) {
                cell = row.createCell(i);
                cell.setCellValue("bar");
            }
            cell = row.getCell(2, Row.RETURN_BLANK_AS_NULL);
            if(cell == null) {
                cell = row.createCell(i);
                cell.setCellValue(0.0);
            }
        }
}

我尝试了很多解决方案,并且我总是得到一个异常NullPointerException。

2 个答案:

答案 0 :(得分:1)

知道哪一行给你例外可能很有用,但我敢打赌这就是这个:

cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {

据我所知,如果单元格为空,则策略RETURN_BLANK_AS_NULL returns a null value。因此,如果在那里得到一个空白单元格,if语句中的cell.getCellType()会引发NullPointerException。

答案 1 :(得分:0)

首先检查NPE,单元格为空:

cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell.getCellType() != Cell.CELL_TYPE_BLANK) {

以后你检查正确:

cell = row.getCell(2, Row.RETURN_BLANK_AS_NULL);
if(cell == null) {

创建新的单元格使用

Row.CREATE_NULL_AS_BLANK
相关问题