数据追加代码如下,非首次写入文件时,使用之前已经写入的文件做模板,进行新数据的追加写入。
public void write(List<Student> students){
String importFile="XXXXXX.xlsx";
File file = new File(importFile);
File tempFile = new File("XXXXXXX_temp.xlsx");
if (file.exists()){
// 第二次按照原有格式,不需要表头,追加写入
EasyExcel.write(file,Student.class).needHead(false).
withTemplate(file).file(tempFile).sheet().doWrite(students);
}else {
// 第一次写入需要表头
EasyExcel.write(file,Student.class).sheet().doWrite(students);
}
if (tempFile.exists()){
file.delete();
tempFile.renameTo(file);
}
}
大概文件大小到达10MB左右,总数据条数在10w+时,doWrite方法会报错,报错信息如下:
Caused by: java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:3236) ~[?:1.8.0_202] at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118) ~[?:1.8.0_202] at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93) ~[?:1.8.0_202] at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153) ~[?:1.8.0_202] at org.apache.poi.openxml4j.opc.internal.MemoryPackagePartOutputStream.write(MemoryPackagePartOutputStream.java:88) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.xmlbeans.impl.store.Cursor._save(Cursor.java:590) ~[xmlbeans-3.1.0.jar:?] at org.apache.xmlbeans.impl.store.Cursor.save(Cursor.java:2544) ~[xmlbeans-3.1.0.jar:?] at org.apache.xmlbeans.impl.values.XmlObjectBase.save(XmlObjectBase.java:223) ~[xmlbeans-3.1.0.jar:?] at org.apache.poi.xssf.usermodel.XSSFSheet.write(XSSFSheet.java:3664) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.poi.xssf.usermodel.XSSFSheet.commit(XSSFSheet.java:3585) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.poi.ooxml.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:490) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.poi.ooxml.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:495) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.poi.ooxml.POIXMLDocument.write(POIXMLDocument.java:236) ~[poi-ooxml-4.1.2.jar:4.1.2] at org.apache.poi.xssf.streaming.SXSSFWorkbook.write(SXSSFWorkbook.java:953) ~[poi-ooxml-4.1.2.jar:4.1.2] at com.alibaba.excel.context.WriteContextImpl.finish(WriteContextImpl.java:381) ~[easyexcel-core-3.2.1.jar:?] at com.alibaba.excel.write.ExcelBuilderImpl.finish(ExcelBuilderImpl.java:99) ~[easyexcel-core-3.2.1.jar:?] at com.alibaba.excel.ExcelWriter.finish(ExcelWriter.java:143) ~[easyexcel-core-3.2.1.jar:?]
使用版本:3.2.1 这种模板追加的方式,是不是会持续把之前已经写入文件的数据加载到内存中?最终造成滚雪球一样的内存开销? 请求大佬出一样真正追加的方法,类似于append,而不是这种rename的方式。