Apache POI:SXSSFWorkbook.dispose()不存在

我使用Apache的POI API来编写XLSX文件。 由于我需要编写大文件,因此我正在使用Streaming API(SXSSF)。 要做到这一点,我遵循本指南。 请注意,在示例的结尾处有一个呼叫

wb.dispose 

这个wb实例引用了一个SXSSFWorkbook实例。 我在我的代码中使用相同的,但它抱怨不存在的处置方法。 我下载了源代码,方法不在那里。 然而,去他们的SVN和检查类的代码,我们可以看到在那里的方法:

https://svn.apache.org/repos/asf/poi/trunk/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java

我已经尝试重新编译他们的代码,但我得到了很多错误…

从2012年12月3日起,POI 3.9作为稳定版发布。 dispose()方法在本发行版的SXSSFWorkbook中可用。

当然,这个问题并不是这样的。

Apache POI 3.8(当时最新的稳定版本)为每个工作表创build临时XML文件(使用SXSSF时),但不提供删除这些文件的选项。 这个事实使得这个API不太好用,因为如果我输出600MB的数据,那么我将有两个600MB的文件,其中一个文件将会在临时文件夹中,直到它被删除。

挖掘代码,我们看到类SXSSFSheet有一个SXSSFSheet的实例。 最后一个类负责编写和维护由File实例表示的临时文件。 访问这个对象将允许删除文件。 所有这些实例都是私有的,理论上你不能访问它们。 但是通过反思,我们可以通过访问File实例来删除这个有用但烦人的文件!

以下方法允许这样做。 通过调用deleteSXSSFTempFiles ,该工作簿的所有临时文件被删除。

 /** * Returns a private attribute of a class * @param containingClass The class that contains the private attribute to retrieve * @param fieldToGet The name of the attribute to get * @return The private attribute * @throws NoSuchFieldException * @throws IllegalAccessException */ public static Object getPrivateAttribute(Object containingClass, String fieldToGet) throws NoSuchFieldException, IllegalAccessException { //get the field of the containingClass instance Field declaredField = containingClass.getClass().getDeclaredField(fieldToGet); //set it as accessible declaredField.setAccessible(true); //access it Object get = declaredField.get(containingClass); //return it! return get; } /** * Deletes all temporary files of the SXSSFWorkbook instance * @param workbook * @throws NoSuchFieldException * @throws IllegalAccessException */ public static void deleteSXSSFTempFiles(SXSSFWorkbook workbook) throws NoSuchFieldException, IllegalAccessException { int numberOfSheets = workbook.getNumberOfSheets(); //iterate through all sheets (each sheet as a temp file) for (int i = 0; i < numberOfSheets; i++) { Sheet sheetAt = workbook.getSheetAt(i); //delete only if the sheet is written by stream if (sheetAt instanceof SXSSFSheet) { SheetDataWriter sdw = (SheetDataWriter) getPrivateAttribute(sheetAt, "_writer"); File f = (File) getPrivateAttribute(sdw, "_fd"); try { f.delete(); } catch (Exception ex) { //could not delete the file } } } }