如何使用Apache POI Event API读取特定行



我想读取大的xls或xlsx文件(大约超过30 MB,有70,000+行)。我能够轻松地使用Apache POI读取小的excel文件,直到我收到OutOfMemory错误。

性能和内存使用是我关心的问题。我阅读了许多帖子,如果内存占用是一个问题,那么对于XSSF,您可以获取底层XML数据,并使用XSSF和SAX(事件API)自己处理它。好吧,我发现它很有趣,现在可以毫无问题地读取整个 xlsx 文件。在不使用事件 API 时,与几乎以 GB 为单位(如果我将 -Xmx 设置为 1024m 并且它仍然用于挂起,则高达 1GB)相比,它消耗的内存要少得多(小于 70 MB)。

但是现在我想自定义读取过程,只允许从 excel 读取特定行。我可以使用org.apache.poi.ss.usermodel.Sheet#getRow(int rownum)轻松做到这一点。但是使用事件 API 它可以不间断地读取所有行,我发现很难读取特定行,例如仅读取行号 2、3、5 等。以下是我的整个代码:

import java.io.InputStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.openxml4j.opc.OPCPackage;
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 org.xml.sax.helpers.XMLReaderFactory;
/**
 * XSSF and SAX (Event API)
 */
public class FromHowTo {
    public void processAllSheets(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader( pkg );
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);
        Iterator<InputStream> sheets = r.getSheetsData();
        while(sheets.hasNext()) {
            InputStream sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
        }
    }
    public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
        XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        ContentHandler handler = new SheetHandler(sst);
        parser.setContentHandler(handler);
        return parser;
    }
    /** 
     * See org.xml.sax.helpers.DefaultHandler javadocs 
     */
    private static class SheetHandler extends DefaultHandler {
        private SharedStringsTable sst;
        private String lastContents;
        private boolean nextIsString;
        Vector values = new Vector(10);
        private SheetHandler(SharedStringsTable sst) {
            this.sst = sst;
        }
        public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
            // c => cell
            if(name.equals("c")) {
                // Figure out if the value is an index in the SST
                String cellType = attributes.getValue("t");
                //System.out.println(cellType);
                if(cellType != null && cellType.equals("s")) {
                    nextIsString = true;
                } else {
                    nextIsString = false;
                }
            }
            // 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) {
                try {
                    int idx = Integer.parseInt(lastContents);
                    lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                } catch (NumberFormatException e) {
                }
            }
            // v => contents of a cell
            // Output after we've seen the string contents
            if(name.equals("v")) {
                values.add(lastContents);
            }
            if(name.equals("row")) {
                System.out.println(values);
                values.removeAllElements();
            }
        }
        public void characters(char[] ch, int start, int length) throws SAXException {
            lastContents += new String(ch, start, length);
        }
    }
    public static void main(String[] args) throws Exception {
        FromHowTo howto = new FromHowTo();
        howto.processAllSheets(args[0]);
    }
}

我正在使用带有Apache POI 3.7的JRE7。有人可以帮我使用事件 API 获取特定行吗?

每个行开始元素都有一个行号。 可以从属性中检索

long rowIndex = Long.valueOf(attributes.getValue("r"));

事件模型将遍历所有行,但您可以在 endElement 中获取索引并相应地处理您的数据

最新更新