2

我需要有关反复出现的问题的帮助。早些时候我问了一个类似的问题,但得到了部分答案。这里的问题 问题是,每次我想在没有任何数据或空白的行上写入时,我总是会遇到空指针错误问题。我的临时解决方案是用数据填充这些行,这样我就可以在每一列上写一些东西。一位帮助我的志愿者给出的解决方案也只是暂时的。我对我的代码做了一些改动(如下)。空指针错误指向带有双星号的行。

public void writeSomething(XSSFWorkbook wb){
        for (String elem: listOfSheetNames){
            if (elem.equals("Sheet2")){

                sheet = wb.getSheet(elem);
                XSSFRow row = sheet.getRow(2);
                **XSSFCell cell = row.getCell(3, Row.CREATE_NULL_AS_BLANK );

                if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
                    cell = row.createCell(3);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue("this was blank");
                }
            }
        }
    }

我继续研究这个问题,我看到他们正在使用这里指出的 MissingCellPolicy继续尝试该代码但它不起作用所以我检查了 Apache Docs 并且他们有 Row.Create_Null_as_Blank 但不确定它是否是与 MissingCellPolicy.Create_Null_as_Blank 相同,或者后者只是在以前的 poi 版本中使用。尽管这应该解决了有关空白列或行的问题。我仍然收到空指针异常错误。如果这有帮助,我正在使用 Apache poi 3.9 版。非常感谢任何帮助。谢谢

更新 1

我使用 jims 解决方案更新了我的代码。我添加了一个方法来检查一行是否存在。但我仍然有两个星号的相同错误显示。这是我的代码:

public void writeSomething(XSSFWorkbook wb){
        for (String elem: listOfSheetNames){
            if (elem.equals("Sheet2")){
                int y=1;
                sheet = wb.getSheet(elem); 
                XSSFRow row = null; //create row variable outside if scope

                if (isRowEmpty(sheet.getRow(4))== false){
                    row = sheet.createRow(4);
                }   

                **XSSFCell cell = row.getCell(y, Row.CREATE_NULL_AS_BLANK );

                if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
                    cell = row.createCell(y);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue("Hooooy this was blank");
                }

            }
        }
    }

isRowEmpty

public boolean isRowEmpty(Row row){

        if (row == null){
            return true;
        }
        else {
            return false;
        }
    }

更新 2

我为我的代码找到了一种解决方法,以防万一有人发现它有用。我没有使用 row.getCell 因为我总是遇到 NUll 指针错误。请参阅下面的代码

public void writeSomething(XSSFWorkbook wb){
        for (String elem: listOfSheetNames){
            if (elem.equals("Sheet2")){
                int y=1; //sets column number
                sheet = wb.getSheet(elem); 
                XSSFRow row = null; //create row variable outside if scope

                if (isRowEmpty(sheet.getRow(19))== false){
                    row = sheet.createRow(19);
                    XSSFCell cell = row.createCell(y);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue("Hooooy this was blank");
                }   

            }
        }
    }
4

1 回答 1

2

如果您需要的单元格不存在,则必须使用

HSSFRow.createCell(int columnIndex, int type) 

同样,如果该行不存在,您可以使用

HSSFSheet.createRow(int rownum)

XSSF 也有相同的方法。

于 2013-01-09T08:04:39.663 回答