Unable to open excel using ApachePOI - Getting Exception

爱⌒轻易说出口 提交于 2019-12-20 04:24:40

问题


While trying to open an excel using ApachePOI I get

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.

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

回答1:


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!

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

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

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


来源:https://stackoverflow.com/questions/12350775/unable-to-open-excel-using-apachepoi-getting-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!