且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

org.apache.poi.openxml4j.exceptions.InvalidOperationException:无法打开指定的文件

更新时间:2022-10-14 21:55:41

有一些问题在这里:

  FIS =新的FileInputStream(新文件(/家庭/阿马尔/桌面/新/ abc.xls));
    工作簿WB =新org.apache.poi.xssf.usermodel.XSSFWorkbook(FIS);

首先,如在Apache POI文档解释,不要使用,如果你的InputStream有一个文件!它的速度较慢,并使用更多的内存

其次,XSSF是code与的.xlsx 文件的工作,但你的文件是一个的.xls 之一,所以这是行不通的。

第三,Apache的POI有code,它会自动找出你的是什么样的文件,并为您创建相应的工作簿

因此​​,您code应改为为

 工作簿WB = WorkbookFactory.create(新文件(/家庭/阿马尔/桌面/新/ abc.xls));

这将创建正确的工作簿,从文件直接

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

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