Unable to open excel using ApachePOI - Getting Exception

后端 未结 1 1576
一整个雨季
一整个雨季 2021-01-25 05:44

While trying to open an excel using ApachePOI I get

org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can\'t open the specified file: \'C:\\Users\\mdw

相关标签:
1条回答
  • 2021-01-25 06:12

    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();
    
    0 讨论(0)
提交回复
热议问题