我正在尝试将 arrayList 的一些元素打印到 excel 中。我使用新创建的没有内容的 excel 文件。
Row row;
Cell column;
int size = records.size(); //records is my ArrayList
try {
//Get the excel file.
FileInputStream file = new FileInputStream(new File("C:\\test\\test.xls"));
//Get workbook for XLS file.
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook.
HSSFSheet sheet1 = workbook.getSheetAt(0);
for(int i=0; i<size; i++){
//here I get the exception
row = sheet1.getRow(i+1);
column = row.getCell(0);
column.setCellValue(records.get(i).getDate()); // this method returns a date..
}
file.close();
FileOutputStream out = new FileOutputStream(new File("my_path\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
所以我将这些行替换为
row = sheet1.getRow(i+1);
if(row.getCell(0)==null){
column = row.createCell(0);
column.setCellValue(records.get(i).getDate());
}else{
row.getCell(0).setCellValue(records.get(i).getDate()); // this method returns a date..
}
但是异常还是出现了。然后我看到这个question , 我试过这个
if(row.getCell(0)==null || getCellValue(row.getCell(0)).trim().isEmpty()){
column = row.createCell(0);
column.setCellValue(records.get(i).getDate());
}else{
row.getCell(0).setCellValue(records.get(i).getDate());
}
和方法
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}
但我仍然遇到异常..
最佳答案
经过很多天,我找到了问题的根源。问题是当该行为空时...具有以下内容
row = sheet1.getRow(i+1);
if(row == null){
row = sheet1.createRow(i+1);
}
程序运行良好。
关于java - 尝试写入 excel 中的空/空白单元格会导致 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32506580/