Unable to open excel using ApachePOI - Getting Exc

2019-03-03 02:15发布

问题:

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