【问题标题】:Cannot invoke "org.apache.poi.ss.usermodel.Cell.setCellValue(String)" because "cell" is null for existing XLSM file无法调用“org.apache.poi.ss.usermodel.Cell.setCellValue(String)”,因为现有 XLSM 文件的“cell”为空
【发布时间】:2021-07-21 19:55:09
【问题描述】:

我使用 Apache POI 将数据写入预定义的 XLSM 文件。我使用此代码打开现有文件:

Cell cell;
File file = new File(XLSMPath);
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook workbook = XSSFWorkbookFactory.createWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(recordcount+4);

数据在第 5 行的第一次迭代中写入,依此类推。设置给定单元格值的代码:

cell = row.getCell(CellReference.convertColStringToIndex("A"));
cell.setCellValue(myvalue);

前 400 次迭代运行良好,但之后我收到以下错误消息:

无法调用“org.apache.poi.ss.usermodel.Cell.setCellValue(String)” 因为“单元格”为空

【问题讨论】:

    标签: java excel apache-poi xlsm


    【解决方案1】:

    您需要自己创建工作表单元格。只需检查您的Cell 是否为null 并使用createCell(int) 创建新的Cell

    cell = row.getCell(CellReference.convertColStringToIndex("A"));
    if (cell == null) {
        // maybe in your case index should be taken in other way
        cell = row.createCell(CellReference.convertColStringToIndex("A")); 
    }
    cell.setCellValue(myvalue);
    

    【讨论】:

    • 谢谢,没关系,我只是想知道,为什么文件有 400 行。
    • 这也让我感到惊讶。当我写下您的问题的答案时,我在文档中寻找这方面的信息,但是我没有找到有关工作簿是使用一定数量的默认列创建的信息(类似于行的情况)。根据我使用 Apache POI 的经验,我可以说我总是必须自己创建行和列。
    猜你喜欢
    • 2021-12-20
    • 2021-04-29
    • 1970-01-01
    • 2022-12-05
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多