简体   繁体   中英

“Exception in thread ”main“ java.lang.NullPointerException” when working with Apache POI, excel, and eclipse?

Here is the snippet of my code:

public static String read1(int rowIndex, int colIndex) {
    String value = new String();
    HSSFWorkbook wb = null;

    try {
        wb = new HSSFWorkbook(new FileInputStream(Words1));
    } catch (Exception e) {
    }

    HSSFSheet sheet = wb.getSheet("SAT");
    HSSFRow row = sheet.getRow(rowIndex - 1);
    HSSFCell cell = row.getCell(colIndex - 1);

    DataFormatter formatter = new DataFormatter();
    value = formatter.formatCellValue(cell);

    return value;
}

Then I have a main class that tells the program to use this method. The problem when I run it is "Exception in thread "main" java.lang.NullPointerException

at Outline.read1(Outline.java:34)

at Outline.main(Outline.java:55)"

where line 34 is this(in the snippet above):

HSSFSheet sheet = wb.getSheet("SAT");

and line 55 is the part that tells the program to go to this method, which is:

String val=read1(rowIndex,colIndex);

I can't, for the life of me, find the reason why this won't run. Thanks!

This:

wb= new HSSFWorkbook(new FileInputStream(Words1));

probably throws an exception, but you don't notice because you are not handling it. And then wb stays null and you get a NullPointerException when calling

HSSFSheet sheet = wb.getSheet("SAT");

Try adding e.printStackTrace(); to the catch block to see if there is an exception thrown:

try {
    wb = new HSSFWorkbook(new FileInputStream(Words1));
} catch (Exception e) {
   e.printStackTrace();
}

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