如何用Java的Apache POI在Excel中插入空值?解决日期字段空指针异常
解决Apache POI写入空Date字段导致的NullPointerException问题
问题根源在于Apache POI的setCellValue(Date)方法无法处理null值,当admissionDate为空时,直接传入会触发底层Calendar的setTime(null)操作,从而抛出NullPointerException。要实现空单元格效果,只需在写入前增加空值判断即可。
修改后的代码如下:
Row studentRow = studentSheet.createRow(0); studentRow.createCell(0).setCellValue("Id"); studentRow.createCell(1).setCellValue("Name"); studentRow.createCell(2).setCellValue("Admission_Date"); int studentCount = 1; for(Student student : listOfStudent) { Row currentRow = accountSheet.createRow(studentCount); currentRow.createCell(0).setCellValue(student.getId()); currentRow.createCell(1).setCellValue(student.getName()); Cell dateCell = currentRow.createCell(2); Date admissionDate = student.getAdmissionDate(); if (admissionDate != null) { dateCell.setCellValue(admissionDate); // 可选:设置日期格式,让Excel正确识别为日期类型 CellStyle dateStyle = accountSheet.getWorkbook().createCellStyle(); CreationHelper creationHelper = accountSheet.getWorkbook().getCreationHelper(); dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd")); dateCell.setCellStyle(dateStyle); } // 若admissionDate为null,不设置单元格值,自然为空 studentCount++; }
关键说明:
- 先创建日期列对应的单元格,再判断
admissionDate是否为null:仅当日期不为空时调用setCellValue(Date),为空则跳过,单元格会保持空状态。 - 可选择性添加日期格式设置,确保Excel将该单元格识别为日期类型,而非普通文本。
内容的提问来源于stack exchange,提问作者Developer007
相关产品推荐
相关产品推荐

