简体   繁体   中英

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?

Try using XSSFWorkbook instead of HSSFWorkbook.

EDIT

As explained here https://poi.apache.org/spreadsheet/

HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.

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

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)

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