Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert a null value in Excel from Java code using ApachePOI

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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++;     
    }    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading