在Apache POI中创建单元格时获取空指针异常

dim*_*mas 1 java apache-poi

每次运行我的代码时,我都会收到一个空指针错误(下面),它指向用两个星号指定的行.

public void writeSomething(XSSFWorkbook wb){
        for (String elem: listOfSheetNames){
            if (elem.equals("Sheet2")){
                sheet = wb.getSheet(elem); //sheet is of type XSSFSheet
                XSSFRow row = sheet.getRow(0);
                **XSSFCell cell = row.getCell(1);

                if (cell == null){
                    cell = row.createCell(1);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue("Apple");
                }                                       
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我是apache poi的新手,我只是想把数据写入第二张excel表(Sheet2)中的空白单元格.我在这里做错了吗?

Mic*_*dan 5

不幸的是,细胞目前null不是空白细胞.将数据放在指定的工作表上会使其变为空白.您可能希望先创建单元格,然后检查它是否是blank单元格而不是null.

**XSSFCell cell = row.createCell(1);

if (cell == Cell.CELL_TYPE_BLANK){
   cell.setCellType(Cell.CELL_TYPE_STRING);
   cell.setCellValue("Apple");
}   
Run Code Online (Sandbox Code Playgroud)