本文介绍了关闭文件句柄的工作簿(Apache的POI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用构造 WorkbookFactory.create(新文件(路径/要/ XLSX))新工作簿。然而,当我尝试启动应用程序后,在Excel中编辑文件,我得到一个错误消息,该文件正在使用中。我一定要释放的文件了,如果是这样,怎么样? (我找不到像 Workbook.close()中的API文档的任何东西)或者,我在其他地方看?

I constructed a new Workbook using WorkbookFactory.create(new File("path/to/xlsx")). However, when I try to edit the File in Excel after starting the application, I get an error message that the file is in use. Do I have to free the file up, and if so, how? (I could not find anything like Workbook.close() in the api docs) Or do I have to look in other places?

我不知道还有什么地方可以看;应用程序不使用CSV和Excel文件,我只需调用转换器(XLS => CSV),这是唯一的区别导致了这些问题。

I have no clue where else to look; the application does not cause these issues with csv and for excel files I simply call the converter (xls => csv) which is the only difference.

(我用POI 3.8)

(I am using POI 3.8)

推荐答案

如果您需要的时候得到的资源封闭的完全控制,你应该创建OPCPackage自己注册前,并传递到WorkbookFactory。 OPCPackage提供你以后close方法。一个工作簿将继续开放,直到垃圾收集

If you need full control of when the resources get closed, you should create the OPCPackage yourself up front, and pass that into WorkbookFactory. OPCPackage provides the close method you're after. A Workbook will remain open until garbage collection

您code看起来是这样的:

Your code would look something like:

     File f = new File("/path/to/excel/file");
     Workbook wb = null;

     NPOIFSFileSystem npoifs = null;
     OPCPackage pkg = null;
     try {
       npoifs = new NPOIFSFileSystem(f);
       wb = WorkbookFactory.create(npoifs);
     } catch(OfficeXmlFileException ofe) {
       pkg = OPCPackage.open(f);
       wb = WorkbookFactory.create(pkg);
     }

     // Use it

     if (npoifs != null) { npoifs.close(); }
     if (pkg != null) { pkg.close(); }

这篇关于关闭文件句柄的工作簿(Apache的POI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:30