简体   繁体   中英

Reading EXCEL file in Java using jxl

I have a problem with reading xls files into Java usin jxl library.

Could you tell me what is wrong my code? I attached below. Something is wrong wif fillData method. The console returns:

Exception in thread "Thread-1" java.lang.NullPointerException
    at StudentLogin.fillData(StudentLogin.java:104)
    at StudentLogin.<init>(StudentLogin.java:70)
    at Login$PBar.run(Login.java:103)
    at java.base/java.lang.Thread.run(Unknown Source)

Thank you in advance for your help.

 public void fillData(File file) {
            Workbook workbook = null;
            try {
                workbook = Workbook.getWorkbook(file);
            }
            catch (Exception e) {
            }

            Sheet sheet = workbook.getSheet(0);

            headers.clear();
            for (int i = 0; i < sheet.getColumns(); i++) {
                Cell cell = sheet.getCell(i, 0);
                headers.add(cell.getContents());
            }

            data.clear();
            for (int j = 1; j < sheet.getRows(); j++) {
                Vector<String> d = new Vector<String>();
                for (int i = 0; i < sheet.getColumns(); i++) {
                    Cell cell = sheet.getCell(i, j);
                    d.add(cell.getContents());
                }
                d.add("\n");
                data.add(d);
            }
        }

I would recommend you to take a look at two parts of the method fillData :

1) try-catch probably hides the problem: in the beginning, you call the method getWorkbook which, according to its java doc , can throw an exception if, for instance, the file does not exist. However, you call the getWorkbook in a try-catch block which does not even print the exception. Consequently, if anything goes wrong you will get a null pointer at workbook.getSheet(0) cause the variable workbook keeps holding a null value (as you assign null in the first line of the method). To avoid this problem you can add a printStackTrace in the catch block. Another option is to add a throws Exception in the method definition and remove the try-catch block. Doing this, you may find the real cause of the null pointer.

 try {
      workbook = Workbook.getWorkbook(file);
 } catch (Exception e) {
      e.printStackTrace();
 }

OR

public void fillData(File file) throws Exception {

 Workbook workbook = Workbook.getWorkbook(file);
 ....
}

2) Is the variable headers globally initialized? I can't see in your code where you initialize the variable headers (doing like headers = new ArrayList() ). If you did not do it, you will get a null pointer at headers.clear() . Moreover, the same problem can happen with the variable data if you don't initialize it.

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