I have a one field with admissionDate in Student object, which is suppose should be null anytime When am inserting that value into the excel using apache poi i am getting NullPointerException. Data type of admissionDate is Date
Below is my code
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 studentRow = accountSheet.createRow(studentCount);
studentRow.createCell(0).setCellValue(student.getId());
studentRow.createCell(1).setCellValue(student.getName());
studentRow.createCell(2).setCellValue(student.getAdmissionDate());
studentCount ;
}
But when admission date is null then i have getting below exception
Exception in thread "main" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1770)
at org.apache.poi.ss.usermodel.DateUtil.getExcelDate(DateUtil.java:86)
at org.apache.poi.xssf.usermodel.XSSFCell.setCellValue(XSSFCell.java:600)
at com.wd.classes.CreateExcelFile.generateExcelFile(CreateExcelFile.java:269)
How can i insert a NULL cell if admissiondate is not available
CodePudding user response:
You should check the date before inserting it into the cell:
for(Student student : listOfStudent) {
Row studentRow = accountSheet.createRow(studentCount);
studentRow.createCell(0).setCellValue(student.getId());
studentRow.createCell(1).setCellValue(student.getName());
if( student.getAdmissionDate() != null) ) {
studentRow.createCell(2).setCellValue(student.getAdmissionDate());
}
studentCount ;
}
CodePudding user response:
You can set blank once you create cell something like below:
for(Student student : listOfStudent) {
Row studentRow = accountSheet.createRow(studentCount);
studentRow.createCell(0).setCellValue(student.getId());
studentRow.createCell(1).setCellValue(student.getName());
(student.getAdmissionDate() != null ?
studentRow.createCell(2).setCellValue(student.getAdmissionDate()) :
studentRow.createCell(2).setBlank());
studentCount ;