使用Apache POI进行低内存写入/读取

5
我正在尝试编写一个相当大的XLSX文件(4M+单元格),但是我遇到了一些内存问题。
由于我还需要读取模板中现有的单元格,所以无法使用SXSSF。
是否有什么方法可以减少内存占用?也许可以结合流式读取和流式写入来完成?

你的文件有多少格式或花哨的东西?是否有可能安排它,使得新行只需要放入新工作表中? - Gagravarr
我们正在编写的大部分内容都是新单元格和新行,但我们必须将公式标记为“脏”的,否则Excel将显示它自己的值。也许值得考虑将其拆分为创建和更新,并仅使用SXSSF进行创建。 - Nicklas A.
2个回答

5
为了处理大量数据并占用较少的内存,最好和我认为唯一的选择是使用SXSSF API。如果您仅需要读取现有单元格的某些数据,则假定您不需要同时读取整个4M+数据。在这种情况下,您可以根据应用程序的要求自行处理窗口大小,并在特定时间仅保留所需的数据量。您可以从以下示例开始查看: http://poi.apache.org/spreadsheet/how-to.html#sxssf
SXSSFWorkbook wb = new SXSSFWorkbook(-1); // turn off auto-flushing and accumulate all rows in memory
// manually control how rows are flushed to disk 
if(rownum % NOR == 0) {
((SXSSFSheet)sh).flushRows(NOR); // retain NOR last rows and flush all others

希望这能帮到你。

1
SXSSF 的问题在于您无法读取已经存在的内容。您可以访问已经写入的内容,但无法访问工作簿中已经存在的内容。 - Nicklas A.
使用事件模型进行读取,可以参考http://poi.apache.org/spreadsheet/how-to.html中的示例 - XSSF和SAX(事件API)。 我自己也用过它,虽然有点复杂,但可以读取大量数据而不会耗尽内存。 您还可以查看http://poi.apache.org/spreadsheet/quick-guide.html中的小样本以获取想法。 - ParoTech
但问题是我们需要读取一个单元格,然后再写入同一个单元格,这可能会有些棘手。 - Nicklas A.

2

我使用了SAX解析器来处理XML文档演示的事件。这是

(注意:此处原文缺少内容,无法翻译完整)
import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import org.apache.poi.openxml4j.opc.PackageAccess;
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.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


public class LowMemoryExcelFileReader {

    private String file;

    public LowMemoryExcelFileReader(String file) {
        this.file = file;
    }

    public List<String[]> read() {
        try {
            return processFirstSheet(file);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }

    private List<String []> readSheet(Sheet sheet) {
        List<String []> res = new LinkedList<>();
        Iterator<Row> rowIterator = sheet.rowIterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            int cellsNumber = row.getLastCellNum();
            String [] cellsValues = new String[cellsNumber];

            Iterator<Cell> cellIterator = row.cellIterator();
            int cellIndex = 0;

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cellsValues[cellIndex++] = cell.getStringCellValue();
            }

            res.add(cellsValues);
        }
        return res;
    }

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    private List<String []> processFirstSheet(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        SheetHandler handler = new SheetHandler(sst);
        XMLReader parser = fetchSheetParser(handler);
        Iterator<InputStream> sheetIterator = r.getSheetsData();

        if (!sheetIterator.hasNext()) {
            return Collections.emptyList();
        }

        InputStream sheetInputStream = sheetIterator.next();
        BufferedInputStream bisSheet = new BufferedInputStream(sheetInputStream);
        InputSource sheetSource = new InputSource(bisSheet);
        parser.parse(sheetSource);
        List<String []> res = handler.getRowCache();
        bisSheet.close();
        return res;
    }

    public XMLReader fetchSheetParser(ContentHandler handler) throws SAXException {
        XMLReader parser = new SAXParser();
        parser.setContentHandler(handler);
        return parser;
    }

    /**
     * See org.xml.sax.helpers.DefaultHandler javadocs
     */
    private static class SheetHandler extends DefaultHandler {

        private static final String ROW_EVENT = "row";
        private static final String CELL_EVENT = "c";

        private SharedStringsTable sst;
        private String lastContents;
        private boolean nextIsString;

        private List<String> cellCache = new LinkedList<>();
        private List<String[]> rowCache = new LinkedList<>();

        private SheetHandler(SharedStringsTable sst) {
            this.sst = sst;
        }

        public void startElement(String uri, String localName, String name,
                                 Attributes attributes) throws SAXException {
            // c => cell
            if (CELL_EVENT.equals(name)) {
                String cellType = attributes.getValue("t");
                if(cellType != null && cellType.equals("s")) {
                    nextIsString = true;
                } else {
                    nextIsString = false;
                }
            } else if (ROW_EVENT.equals(name)) {
                if (!cellCache.isEmpty()) {
                    rowCache.add(cellCache.toArray(new String[cellCache.size()]));
                }
                cellCache.clear();
            }

            // Clear contents cache
            lastContents = "";
        }

        public void endElement(String uri, String localName, String name)
                throws SAXException {
            // Process the last contents as required.
            // Do now, as characters() may be called more than once
            if(nextIsString) {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                nextIsString = false;
            }

            // v => contents of a cell
            // Output after we've seen the string contents
            if(name.equals("v")) {
                cellCache.add(lastContents);
            }
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
            lastContents += new String(ch, start, length);
        }

        public List<String[]> getRowCache() {
            return rowCache;
        }
    }
}

1
我尝试了你的代码,恰好注意到它没有读取最后一行,你知道这个问题吗? - Paolo Forgia
看起来要处理空单元格,单元格必须有样式。如果您检查来自Excel的生成的XML文件,如果它包含样式,则会出现在XML文件中。没有数据标记的空单元格(足以使用上面的代码)。 - DaviM
随意更新代码,因为我很久以前使用过它。也许库的最新版本可以解决这个问题或提供另一种解决方法。 - Yan Khonski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接