我有个问题:

我正在使用以下Java代码从Excel文件中读取一些信息:

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


但出现此错误,但我没有“标题”信息:

java.lang.NullPointerException


我在此行有此错误:

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


现在,如何检查“标题”值(或其他值)是否存在,如果这种情况给我一个错误?

最佳答案

您需要确保summaryInfo不为空。

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

10-07 19:07