无法使用ApachePOI打开Excel – 获取exception

在尝试使用ApachePOI打开excel时,我得到了

org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: 'C:\Users\mdwaipay\AppData\Local\Temp\poifiles\poi-ooxml-1570030023.tmp'

我检查了。 没有创建此类文件夹。 我正在使用Apache POI版本3.6。

有帮助吗? 类似的代码在不同的工作区中运行良好。 在这里失去了思想。

码:

 public Xls_Reader(String path) { this.path=path; try { fis = new FileInputStream(path); workbook = new XSSFWorkbook(fis); sheet = workbook.getSheetAt(0); fis.close(); } catch (Exception e) { e.printStackTrace(); } } 

你为什么要把一个非常好的文件包装在一个InputStream ,然后要求POI必须为你缓冲整个批次以便它可以随机访问? 如果你直接将文件传递给POI,生活会好得多,所以它可以根据需要跳过!

如果要同时使用XSSF(.xlsx)和HSSF(.xls),请将代码更改为

 public Xls_Reader(String path) { this.path = path; try { File f = new File(path); workbook = WorkbookFactory.create(f); sheet = workbook.getSheetAt(0); } catch (Exception e) { e.printStackTrace(); } } 

如果您只需要XSSF支持,并且/或者您需要完全控制资源何时关闭,而是执行类似的操作

 OPCPackage pkg = OPCPackage.open(path); Workbook wb = new XSSFWorkbook(pkg); // use the workbook // When you no longer needed it, immediately close and release the file resources pkg.close();