1
votes

I need to read file excel, and I am working with java spring boot, Apache poi. they told us

When working with the newer .xlsx file format, you would use the XSSFWorkbook, XSSFSheet, XSSFRow, and XSSFCell classes. To work with the older .xls format, use the HSSFWorkbook, HSSFSheet, HSSFRow, and HSSFCell classes.

this is my code:


    Workbook workbook;
            if (FileExtension == "xlsx"){
                workbook = new XSSFWorkbook(excelFile);
            }
            else if (FileExtension == "xls"){
                workbook = new HSSFWorkbook(excelFile);
            }
Sheet datatypeSheet = workbook.getSheetAt(0);

Now im getting "workbook" might not have been initialized. How to solve that?

6

6 Answers

3
votes

Current apache poiversions provide WorkbookFactory. Using the create methods of that class there is no need for determining the file format (XSSF or HSSF) by file extension. The WorkbookFactory.create methods are creating XSSFWorkbook or HSSFWorkbook dependent of the file contents found.

So do using:

...
Workbook workbook = WorkbookFactory.create(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
...
1
votes

I think what you want to express is this...

Workbook workbook;
if (FileExtension == "xlsx"){
    workbook = new XSSFWorkbook(excelFile);
}
// for other case
else{
    workbook = new HSSFWorkbook(excelFile);
}
Sheet datatypeSheet = workbook.getSheetAt(0);

Notice the comment in the code, I am sure can investigate the difference by yourself, whick helps a lot.

1
votes

You need to use xmlbeans3.1 instead of xmlbeans4.0.

0
votes

Try this...

Workbook workbook = null;
0
votes

Not initialized.. you should do this

Workbook wb;

wb = Workbook.getWorkbook(new File("d:\\test\\book1.xls"));
0
votes

I believe it is apart of JVM issues, but initializing and declaring at the sometime is sometimes the only way. Try this:

        if (FileExtension == "xlsx"){
               Workbook workbook = new XSSFWorkbook(excelFile);
        }
        else if (FileExtension == "xls"){
              Workbook workbook = new HSSFWorkbook(excelFile);
        }

Sheet datatypeSheet = workbook.getSheetA