【问题标题】:Getting null pointer exception in creating cell in Apache POI在 Apache POI 中创建单元格时出现空指针异常
【发布时间】:2013-01-09 01:50:27
【问题描述】:

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

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

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

【问题讨论】:

  • 错误出现在哪一行?
  • @MichaelArdan 问题清楚地说它指向用两个星号指定的行。**XSSFCell cell = row.getCell(1);
  • @smit 抱歉没有读到后面的短语(下)
  • 好吧,伙计们......我的代码在我将一些随机数据位放在第二张 Excel 表中后实际上工作了。我不知道为什么会这样。我现在只是担心每次我想写一张新纸时我都会继续这样做:/

标签: java apache-poi


【解决方案1】:

很遗憾,当前单元格是null,而不是空白单元格。将数据放在指定的工作表上会使其空白。您可能需要先创建单元格,然后检查它是否是 blank 单元格而不是 null

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

if (cell == Cell.CELL_TYPE_BLANK){
   cell.setCellType(Cell.CELL_TYPE_STRING);
   cell.setCellValue("Apple");
}   

【讨论】:

  • 谢谢迈克尔,我会试试这个。
【解决方案2】:

这会导致类型不兼容。

改为这样做:

if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
    cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue("Apple");
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多