Musich87
Musich87

Reputation: 572

How can I check if an information is present or not in Excel file using Apache POI and Java Code

I have a question:

I'm reading some information from my Excel file using this Java code:

HSSFWorkbook workbook = null;
try {
    workbook = new HSSFWorkbook(file);
}catch (IOException ex) {
   ...
}

SummaryInformation summaryInfo = workbook.getSummaryInformation();

if (summaryInfo.getTitle() != null) {
    System.out.println(summaryInfo.getTitle());
}
if (summaryInfo.getAuthor() != null) {
    System.out.println(summaryInfo.getAuthor());
}

but I get this error I don't have the "Title" information:

java.lang.NullPointerException 

I have this error on this line:

if (summaryInfo.getTitle() != null) {

Now, How can I check if the "Title" value (or other value) is present or not if this condition give me an error?

Upvotes: 1

Views: 290

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66714

You need to ensure that the summaryInfo is not null.

SummaryInformation summaryInfo = workbook.getSummaryInformation();
if (summaryInfo != null) {
    if (summaryInfo.getTitle() != null) {
        System.out.println(summaryInfo.getTitle());
    }
    if (summaryInfo.getAuthor() != null) {
        System.out.println(summaryInfo.getAuthor());
    }
}

Upvotes: 2

Related Questions