首页 文章

使用apache poi api无法修改excel中的工作表

提问于
浏览
0

我正在使用Apache poi api for java写入excel工作簿中的现有工作表 . 我的问题是,在我试图编辑的工作表中,如果行中的任何单元格不为空,即在其中有某种某种值,则程序运行正常并编辑该行中的任何特定单元格 . 例如,如果我的工作表(1,1)中的单元格包含一个值,那么程序编辑同一行的其他单元格(1,5)或(1,12)等等就没有问题 . 但是如果我的整行是空的,即所有单元格都包含null,那么代码会抛出一个nullpointer异常,我无法弄清楚如何删除 . 这是我用于我的项目在我的excel类中编写特定单元格的write方法 .

public void write(int row, int column, String label) {


    try {
        InputStream inp = new FileInputStream(filePath);
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        Row sheetRow = sheet.getRow(row);
        Cell cell = sheetRow.getCell(column);
        //String cellContents = cell.getStringCellValue();
        //        //Modify the cellContents here
        //        // Write the output to a file
        if (cell == null) {
            cell = sheetRow.createCell(column);
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(label);
        FileOutputStream fileOut = new FileOutputStream(filePath);
        wb.write(fileOut);
        fileOut.close();
    } catch (IOException ex) {
        Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex);
    }
}

java抛出在未触及的即空行中编辑单元格的例外情况是:

Exception in thread "main" java.lang.NullPointerException
at seleniumtest.ExcelManipulator.write(ExcelManipulator.java:76)
at seleniumtest.SeleniumTest.main(SeleniumTest.java:28)

Java结果:1

任何人都可以帮我摆脱这个,这样即使整行都是空的,我的代码也会编写一个单元格吗?谢谢

1 回答

  • 3

    我不确定't know exactly where the NPE is thrown, but I'我非常确定ExcelManipulator.java的第76行是这一行: Cell cell = sheetRow.getCell(column);

    正如API for Sheet中所述,如果你要求一个未定义的行,你会得到一个null - 如果整行都是空的话就是这种情况 .

    所以你可以在上面提到的行之前插入 if(sheetRow == null){sheetRow = sheet.createRow(row);} ,你应该没问题 .

相关问题