org.apache.poi.openxml4j.exceptions.InvalidOperationException:无法打开指定的文件
问题描述:
我的代码不工作,它总是显示上述异常。 但我总是可以看到正在生成的tmp文件。org.apache.poi.openxml4j.exceptions.InvalidOperationException:无法打开指定的文件
这里是代码,可以有人请建议的内容:
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();
}
}
答
我能解决我的问题。 我在Linux上工作,所以它被保存在文件中的旧版本的Excel
的
答
有一些问题在这里:
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
首先,as explained in the Apache POI documentation,不,如果你有使用的InputStream一份文件!它更慢,并使用更多的内存
其次,XSSF是与.xlsx
文件一起使用的代码,但您的文件是.xls
之一,所以这将不起作用。
第三,Apache的POI有代码,它会自动计算出你是什么样的文件,并创建相应的工作簿您
你的代码,因此应改为
Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls"));
这将创建正确的工作簿,直接从文件
是,这正是我所认识和使用WorkbookFactory代替。 – 2014-09-24 11:33:45
感谢分享 – 2014-09-24 11:34:08
是'wb = new XSSFWorkbook(spreadSheetFileName);'同样好,其中'spreadSheetFileName'是一个'String'吗? – mbmast 2016-05-21 22:37:36