简体   繁体   中英

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?

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM