Java堆空间错误-将多个Excel文件合并到一个工作簿中(具有多个工作表)

时间:2019-07-11 00:04:32

标签: java excel memory apache-poi heap

我正在尝试使用Java程序将25个单独的Excel文件合并为一个包含25张纸的Excel工作簿。我可以轻松地复制/粘贴工作表,但是我想用代码解决它。我下面的代码适用于25张纸中的24张;但是,我最大的工作表有760,000行数据(其余的只有大约1000行),并且每当我运行该程序时,由于Java Heap Space错误,它就会中断。

我读到一个可能的解决方案是简单地增加堆空间,但这不是一个好习惯。如何使我的程序占用更少的堆内存?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelCombiner {
    private FileList fileList = new FileList();
    private Workbook workbook = new XSSFWorkbook();

    public void createWorkbook() throws IOException, InvalidFormatException {
        FileOutputStream out = new FileOutputStream(new File("MIMIC_DATABASE.xlsx"));
        createSheets();
        workbook.write(out);
        out.close();
        workbook.close();
    }

    public void createSheets() throws InvalidFormatException, IOException {
        for (File file : fileList.getFiles()) {
            System.out.println(file.getName());
            Workbook fileBook = new XSSFWorkbook(file);

            String sheetName = file.getName().replace(".xlsx", "");
            //New Sheet in Workbook that we're copying info into
            Sheet newSheet = workbook.createSheet(sheetName);
            //Old Sheet, fileBook should just be an excel file with one sheet
            Sheet oldSheet = fileBook.getSheetAt(0);

            for (int i = 0; i < oldSheet.getLastRowNum(); i++) {
                Row row = oldSheet.getRow(i);
                Row newRow = newSheet.createRow(i);
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    Cell newCell = newRow.createCell(j);

                    //Make sure to convert all old cells into String/Text
                    //Then copy them over to newCell
                    DataFormatter dataFormatter = new DataFormatter();
                    String cellValue = dataFormatter.formatCellValue(cell);
                    newCell.setCellValue(cellValue);
                }
            }
            fileBook.close();
        }
        //workbook.close();
    }

    public static void main(String[] args) throws IOException, InvalidFormatException {
        ExcelCombiner excelCombiner = new ExcelCombiner();
        excelCombiner.createWorkbook();
    }
}

0 个答案:

没有答案