获取错误“您的InputStream既不是OLE2stream,也不是OOXMLstream”通过Apache POI创build文件时

我正在尝试检查我的excel文件是否已经存在。 如果它不存在,我想创build一个新的,如果它存在,我将删除它并创build一个新的。 我写了下面的程序,但我得到错误在线 – workbook = WorkbookFactory.create(instream);

错误是 – > java.lang.IllegalArgumentException:您的InputStream既不是OLE2stream,也不是在org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:89)在tryIng.main(tryIng的.java:84)

这是一个程序 – >

try { String filePath= "C:/Users/pritik/Desktop/t1.xlsx"; File file = new File(filePath); filePath= file.getAbsolutePath(); xlFile = new File(filePath); if(xlFile.exists() && !xlFile.isDirectory()) xlFile.delete(); //delete if file already exists. xlFile.createNewFile(); inStream = new FileInputStream(xlFile); workbook = WorkbookFactory.create(inStream); // I get error at this line String sheetName="NewSheet"; Sheet sheet = workbook.createSheet(sheetName); FileOutputStream fOut = new FileOutputStream(xlFile); int i,j; xRows = xTS.length; xCols = xTS[0].length; for(i =0;i<xRows;i++) { row = sheet.createRow(i); for(j=0;j<xCols;j++) { cell = row.createCell(j); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(xTS[i][j]); } } workbook.write(fOut); fOut.flush(); fOut.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } 

不要创build一个空文件并尝试阅读它,这将无法正常工作。 一个空的零字节文件是无效的,不能被加载相反,让POI为你创build一个新的文件,你将在以后写。

更改代码:

 if(xlFile.exists() && !xlFile.isDirectory()) xlFile.delete(); //delete if file already exists. xlFile.createNewFile(); inStream = new FileInputStream(xlFile); workbook = WorkbookFactory.create(inStream); 

要改为:

 if(xlFile.exists() && !xlFile.isDirectory()) xlFile.delete(); //delete if file already exists. if (xlFile.toString().endsWith(".xls") { workbook = new HSSFWorkbook(); } else { workbook = new XSSFWorkbook(); } 

另外,如果您想读取现有的文件,请不要在有文件的情况下使用stream。 请参阅POI文档的这一部分 。