java 无法使用 ApachePOI 打开 excel - 出现异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12350775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:31:54  来源:igfitidea点击:

Unable to open excel using ApachePOI - Getting Exception

javaapache-poi

提问by some_other_guy

While trying to open an excel using ApachePOI I get

在尝试使用 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'

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

I checked. No such folder is being created. I am using Apache POI version 3.6.

我检查了。没有创建这样的文件夹。我正在使用 Apache POI 3.6 版。

Any help? A similar code was running fine in a different workspace. At loss of thoughts here.

有什么帮助吗?类似的代码在不同的工作区中运行良好。在这里不知所措。

Code:

代码:

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

回答by Gagravarr

Why are you taking a perfectly good file, wrapping it in an InputStream, then asking POI to have to buffer the whole lot for you so it can do random access? Life is much better if you just pass the File to POI directly, so it can skip about as needed!

为什么您要获取一个完美的文件,将其包装在一个InputStream. 如果你直接将文件传递给 POI,生活会好得多,所以它可以根据需要跳过!

If you want to work with both XSSF (.xlsx) and HSSF (.xls), change your code to be

如果您想同时使用 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();
  } 
}

If you only want XSSF support, and/or you need full control of when the resources get closed, instead do something like

如果您只需要 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();