Vichitra Prani
Vichitra Prani

Reputation: 41

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

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();
    }
    }

Upvotes: 3

Views: 20390

Answers (2)

Gagravarr
Gagravarr

Reputation: 48326

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

Upvotes: 2

Vichitra Prani
Vichitra Prani

Reputation: 41

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

Upvotes: 1

Related Questions