java – Apache POI超出了GC开销限制

前端之家收集整理的这篇文章主要介绍了java – Apache POI超出了GC开销限制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有13个.xlsx文件,每个文件大约有1000行.现在我想用一张表将它合并到一个.xlsx文件中.我在这里使用代码
http://blog.sodhanalibrary.com/2014/11/merge-excel-files-using-java.html#.Vi9ns36rSUk. @H_404_3@这是我的代码(几个更改,addSheet方法不变)

try {
        FileInputStream excellFile1 = new FileInputStream(new File("tmp_testOut1000.xlsx"));
        XSSFWorkbook workbook1 = new XSSFWorkbook(excellFile1);
        XSSFSheet sheet1 = workbook1.getSheetAt(0);

        for(int i = 2; i < 14; i++){
            FileInputStream excellFile2 = new FileInputStream(new File("tmp_testOut" + i + "000.xlsx"));
            XSSFWorkbook workbook2 = new XSSFWorkbook(excellFile2);
            XSSFSheet sheet2 = workbook2.getSheetAt(0);
            System.out.println("add " + i);
            addSheet(sheet1,sheet2);
        }

        excellFile1.close();

        // save merged file
        System.out.println("merging");
        File mergedFile = new File("merged.xlsx");
        if (!mergedFile.exists()) {
            mergedFile.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(mergedFile);
        System.out.println("write");
        workbook1.write(out);
        out.close();
        System.out.println("Files were merged succussfully");
    } catch (Exception e) {
        e.printStackTrace();
    }
@H_404_3@所有文件都在加载和合并但是在“写入”sysout后我得到了

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at org.apache.xmlbeans.impl.store.Xobj.new_cursor(Xobj.java:1829)
at org.apache.xmlbeans.impl.values.XmlObjectBase.newCursor(XmlObjectBase.java:293)
at org.apache.xmlbeans.impl.values.XmlComplexContentImpl.arraySetterHelper(XmlComplexContentImpl.java:1151)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontsImpl.setFontArray(Unknown Source)
at org.apache.poi.xssf.model.StylesTable.writeTo(StylesTable.java:424)
at org.apache.poi.xssf.model.StylesTable.commit(StylesTable.java:496)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:341)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:345)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:206)
at Start.main(Start.java:275)
@H_404_3@我能做什么?为什么会发生这种情况以及如何预防?

解决方法

众所周知,POI需要占用大量内存,因此在处理大型Excel文件时,内存耗尽并不少见. @H_404_3@当您能够加载所有原始文件并且只在编写合并文件时遇到问题,您可以尝试使用SXSSFWorkbook而不是XSSFWorkbook,并在添加一定量的内容后定期刷新(请参阅org.apache.poi的poi文档) .xssf.streaming包).这样,您不必将整个生成文件保留在内存中,而只需保留一小部分.

原文链接:https://www.f2er.com/java/126869.html

猜你在找的Java相关文章