Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file

Tags:

apache-poi

My code is not working, it always shows the above mentioned exception. but I can always see the tmp file being generated.

here is the code, can someone please suggest something:

FileInputStream fis =null;
        try{
        fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));

        Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
                int numOfSheets = wb.getNumberOfSheets();
System.out.println("bhargo num of sheets is " + numOfSheets);
        for(int i=0; i<numOfSheets; i++){
            org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = (Cell) cellIterator.next();
                    if (cell.getCellType() == cell.CELL_TYPE_STRING) {
                        System.out.println("bhargo cell value is " + cell.getStringCellValue().trim());
                    }
                }
            }
            }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        System.out.println("bhargo, closing the stream");
    try {
        fis.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
like image 237
Vichitra Prani Avatar asked Feb 05 '26 07:02

Vichitra Prani


2 Answers

There are a number of issues here:

    fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
    Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);

Firstly, as explained in the Apache POI documentation, don't use an InputStream if you have a file! It's slower and uses more memory

Secondly, XSSF is the code for working with .xlsx files, but your file is a .xls one, so that won't work.

Thirdly, Apache POI has code which will automatically work out what kind of file yours is, and create the appropriate workbook for you

Your code should therefore instead be

Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls"));

This will create the right kind of workbook, direct from the file

like image 140
Gagravarr Avatar answered Feb 12 '26 22:02

Gagravarr


I was able to solve my problem. I am working on linux so it was saving the file in the older version of excel

like image 29
Vichitra Prani Avatar answered Feb 12 '26 20:02

Vichitra Prani



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!