Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Excel from Apache poi java

I'm having a weird problem about reading excel file, I created a file to test but still have the same problem, the workbook is returning that has 0 sheets but it does have 3 sheets: here's my code:

FileInputStream fs = new FileInputStream(new File("C:/Users/TO124415/Desktop/test.xlsx"));

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet hs = wb.getSheetAt(0);
    int number = wb.getNumberOfSheets();
    System.out.println(number);
    FormulaEvaluator form = wb.getCreationHelper().createFormulaEvaluator();
    HSSFCell value = wb.getSheetAt(0).getRow(14).getCell(1);
            for (Row rw : hs){
        for(Cell cell : rw){
            switch(form.evaluateInCell(cell).getCellType()){
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                System.out.println(cell.getStringCellValue());
            }
        }
    }

I'm having this error:

Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (0) is out of range (no sheets)

This error must be if I set getSheetAt(3) because I know that the index is starting from 0 not 1. Someone can explain please?

like image 430
Dev web Avatar asked Mar 07 '26 14:03

Dev web


2 Answers

Your problem is that you're not loading your file, you're creating a new one. These lines here:

FileInputStream fs = new FileInputStream(new File("C:/Users/TO124415/Desktop/test.xlsx"));

HSSFWorkbook wb = new HSSFWorkbook();

Open a file for reading, then promptly ignore it and create a brand new empty workbook. An empty workbook with no sheets in it, which is why you're getting the error about there being no sheets....

You instead want to do something like:

File input = new File("C:/Users/TO124415/Desktop/test.xlsx");
Workbook wb = WorkbookFactory.create(input);

That will read in the contents of the workbook, and auto-detect the type too for you (so you can use XLS and XLSX)

like image 141
Gagravarr Avatar answered Mar 10 '26 04:03

Gagravarr


It looks, you are using the wrong file type for the unsupported Class.

HSSFWorkbook class will support only .xls file type whreas XSSFWorkbook class will support both .xls and .xlsx file type

Please do any one of the below steps

  1. Change the file extension as .xls (.xlsx file is supported only in XSSF not in HSSF.)
  2. Change the HSSF as XSSF by keeping the xlsx file extension
like image 35
Subburaj Avatar answered Mar 10 '26 02:03

Subburaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!