我需要在工作簿的工作表中添加行。我正在使用org.apache.poi.xssf.streaming.SXSSFWorkbook,但我无法实现低内存占用。代码如下:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelHelper {
public static void createExcelFileWithLowMemFootprint(
ArrayList<HashMap<String, Object>> data,
ArrayList<String> fieldNames, String fileName, int rowNum) {
try {
if (rowNum == 0) {
// Creating a new workbook and writing the top heading here
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
Sheet worksheet = workbook.createSheet("Sheet 1");
int i = 0;
Iterator<String> it0 = fieldNames.iterator();
Row row = worksheet.createRow(i);
int j = 0;
while (it0.hasNext()) {
Cell cell = row.createCell(j);
String fieldName = it0.next();
cell.setCellValue(fieldName);
j++;
}
rowNum++;
FileOutputStream fileOut = new FileOutputStream(fileName);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}
InputStream fileIn = new BufferedInputStream(new FileInputStream(
fileName), 1000);
SXSSFWorkbook workbook = new SXSSFWorkbook(
new XSSFWorkbook(fileIn), 1000);
Sheet worksheet = workbook.getSheetAt(0);
Iterator<HashMap<String, Object>> it = data.iterator();
int i = rowNum;
while (it.hasNext()) {
Row row = worksheet.createRow(i);
int j = 0;
HashMap<String, Object> rowContent = it.next();
Iterator<String> it1 = fieldNames.iterator();
while (it1.hasNext()) {
Cell cell = row.createCell(j);
String key = it1.next();
Object o = rowContent.get(key);
if (o instanceof String) {
cell.setCellValue((String) o);
} else if (o instanceof Double) {
cell.setCellType(cell.CELL_TYPE_NUMERIC);
cell.setCellValue((Double) o);
}
j++;
}
i++;
}
fileIn.close();
FileOutputStream fileOut = new FileOutputStream(fileName);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我通过批量传递内容(以便在jvm内存上保存)并通过增加变量rowNum来附加到文件。
根据我的理解,当我用
重新打开文件时SXSSFWorkbook workbook = new SXSSFWorkbook(new XSSFWorkbook(fileIn),1000);
XSSWorkbook的构造函数在内存中重新加载整个文件,导致超过gc限制。
我浏览了http://poi.apache.org/spreadsheet/how-to.html,但无法找到适合我用例的解决方案。
你们能建议如何解决这个问题,以实现低内存占用附加行到工作簿吗?
SXSSFWorkbook
不需要输出,然后加载回良好的内存管理。只需一次写入所有数据。如果您尝试加载整个工作簿,它会将其存储在内存中,当立即写入时,它会使用存储空间。在某些计算机上,1000
在构造函数中也需要大量的代码。如果你想,试着把100
或其他一些较低的数字在构造函数中,而不是1000
。