1

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

2 Answers 2

4

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++;     
    }    
Sign up to request clarification or add additional context in comments.

Comments

1

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++;  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.