我需要有关重复出现的问题的帮助。早些时候我问过类似的问题,但得到了部分回答。问题here 问题是,每次我想在没有任何数据或空白的行上写入时,我总是遇到空指针错误问题。我的临时解决方案是用数据填充这些行,这样我就可以在每一列上写一些东西。另外,一位帮助我的志愿者给出的解决方案只是暂时的。我对我的代码做了一些修改(如下)。 空指针错误指向带有双星号的行。
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 指示 here我继续尝试该代码,但它不起作用,所以我检查了 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");
}
}
}
}
最佳答案
如果您需要的单元格不存在,您必须使用
创建它HSSFRow.createCell(int columnIndex, int type)
同样,如果该行不存在,则使用以下命令创建它
HSSFSheet.createRow(int rownum)
XSSF 也有相同的方法。
关于java - 使用 Apache POI 的空白列和行的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14228887/