1

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(); 
  } 
}
6
  • what is the excel version you are using. Commented Sep 10, 2012 at 12:51
  • Why are you not using the latest version of Apache POI? It has lots of bug fixes! Commented Sep 10, 2012 at 12:52
  • Well thanks for the interest. @swamy: It worked well with another excel. Both .xlsx Any idea what can be the reason? :P Commented Sep 11, 2012 at 19:11
  • @Gagravarr: Updated the version too. :) Commented Sep 11, 2012 at 19:12
  • How are you opening the file? With a File object or an InputStream one? And if the latter, did you try with the former? Commented Sep 11, 2012 at 20:37

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man. I had this fixed after upgrading my POI and using a fresh excel.
Even with the new version, open from a File if you can, not an InputStream - it'll be quicker and use less memory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.