apachepoi:outofmemory

332nm8kg  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(376)

我正在为kindle fire开发一个应用程序,它从dropbox中提取一个.xlsx文件,并使用ApachePOI将数据解析到一个sqlite数据库中(一个表有10个属性—一旦解析成功,我将把它分解成更多的表)。这个文件只有2mb(约28000行,每行10列),所以当我开始在物理设备上测试时(emulator工作正常,但速度非常慢),我遇到了outofmemoryerrors。我做了大量的挖掘,发现我可以实现sax来减少我使用的内存量。但是,我不太确定如何将所有数据放入表中—根据我看到的示例代码,每个单元格(至少从我所知道的情况来看)都是单独计算的,所以我不能对每行迭代进行一次查询。我遇到的另一个问题是,我有一列数字(价格)打印到控制台(通过debug.print())两次,我不知道为什么。我对这件事简直不知所措——我花了好几天时间来解决dropbox和poi的不同问题,但这件事让我很为难。到目前为止,我使用这三个作为模板/指南(主要是后者):
http://www.saxproject.org/quickstart.html
https://github.com/apache/poi/blob/230453d76e6e912dfa22088544488a0a6baf83a2/src/ooxml/java/org/apache/poi/xssf/eventusermodel/xssfsheetxmlhandler.java
https://dzone.com/articles/introduction-to-apache-poi-library
我已经讨论过这些(还有其他几个):
如何读取大小大于40mb的xlsx文件
http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/fromhowto.java
http://poi.apache.org/components/spreadsheet/how-to.html#xssf_sax_api
使用poi的xssf和sax(事件api)读取excel表
https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/xlsx2csv.java
这是一个相当简单的应用程序,所以我不需要任何太花哨的东西-只需要在这一点上运行。所以我想我的问题是:sax是避免内存问题的最好方法吗?如果是这样,我如何实现它来将每一行准确地解析到我的数据库中?如果没有,我应该往哪个方向走?下面是我的解析类的内容(runningtime和isparsing用于测试):

import android.content.Context;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
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 org.xml.sax.helpers.XMLReaderFactory;

public class ExcelParser {
    public static boolean isParsing = false;
    private DBHelper dbHelper;
    private File dropboxFile;

    // purpose: parameterized constructor
    // parameters: FileInputStream inputStream
    // returns: nothing
    public ExcelParser(Context context, File dropboxFile) {
        this.dropboxFile = dropboxFile;
        dbHelper = new DBHelper(context);
    }// end ExcelParser(FileInputStream inputStream)

    // purpose: parses the inputStream (.xlsx) into a list of Product objects
    // parameters: none
    // returns: void
    public void parseToDB() {
        Long runningTime = System.currentTimeMillis();

        isParsing = true;
        Debug.print(this.getClass().getSimpleName(), "----- STARTING -----");

        try {
            OPCPackage pkg = OPCPackage.open(dropboxFile);
            XSSFReader xssfReader = new XSSFReader(pkg);
            SharedStringsTable sharedStringsTable = xssfReader.getSharedStringsTable();
            XMLReader parser = getSheetParser(sharedStringsTable);

            Iterator<InputStream> sheets = xssfReader.getSheetsData();
            Debug.print(this.getClass().getSimpleName(), "sheet processing");
            while(sheets.hasNext()) {
                Debug.print(this.getClass().getSimpleName(), "Processing sheet");

                InputStream sheet = sheets.next();
                InputSource sheetSource = new InputSource(sheet);
                parser.parse(sheetSource);
                sheet.close();

                Debug.print(this.getClass().getSimpleName(), "Done processing sheet");
            }// end while-loop
        } catch (SAXException | OpenXML4JException | IOException e) {
            e.printStackTrace();
        } finally {
            isParsing = false;
            Debug.print(this.getClass().getSimpleName(), "----- FINISHED : " + ((System.currentTimeMillis() - runningTime) / 1000) + " seconds -----");
        }// end try-catch
    }// end parseToDB()

    //
    public XMLReader getSheetParser(SharedStringsTable sharedStringsTable) throws SAXException {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        ContentHandler handler = new SheetHandler(sharedStringsTable);
        parser.setContentHandler(handler);

        return parser;
    }// end getSheetParser(SharedStringsTable sharedStringsTable)

    // SHEET HANDLER CLASS
    private static class SheetHandler extends DefaultHandler {
        private SharedStringsTable sharedStringsTable;
        private boolean fromSST, isCellValue, isNumber;
        private String contents;

        //
        private SheetHandler(SharedStringsTable sharedStringsTable) {
            this.sharedStringsTable = sharedStringsTable;
        }// end SheetHandler(SharedStringsTable sharedStringsTable)

        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
            // clear contents cache
            contents = "";

            // element row represents Row
            if(name.equals("row")) {
                String rowNumStr = attributes.getValue("r");
                Debug.print(this.getClass().getSimpleName(), "Row# " + rowNumStr);
            }
            // element c represents Cell
            else if(name.equals("c")) {
                // attribute r represents the cell reference
                Debug.print(this.getClass().getSimpleName(), attributes.getValue("r") + " - ");

                // attribute t represents the cell type
                String cellType = attributes.getValue("t");
                if (cellType != null && cellType.equals("s")) {
                    // cell type s means value will be extracted from SharedStringsTable
                    fromSST = true;
                } else if(cellType == null) {
                    // *likely a number
                    isNumber = true;
                }
            }
            // element v represents value of Cell
            else if(name.equals("v")) {
                isCellValue = true;
            }
        }// end startElement(String uri, String localName, String name, Attributes attributes)

        @Override
        public void characters(char[] ch, int start, int length) {
            if(isCellValue)
                contents += new String(ch, start, length);
        }// end characters(char[] ch, int start, int length)

        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            if(isCellValue) {
                if(fromSST) {
                    int index = Integer.parseInt(contents);
                    contents = new XSSFRichTextString(sharedStringsTable.getEntryAt(index)).toString();

                    Debug.print(this.getClass().getSimpleName(), "Contents: " + contents + " >>");

                    isCellValue = false;
                    fromSST = false;
                } else if(isNumber) {
                    Debug.print(this.getClass().getSimpleName(), "Contents (num?): " + contents + " >>");
                }
            }
        }// end endElement(String uri, String localName, String name)
    }// end class SheetHandler
}// end class ExcelParser
x6yk4ghg

x6yk4ghg1#

多亏了@gagravarr的建议,我才想出了一个解决办法。我找到了xlsx2csv.java文件的更新实现(同时寻找一种有效的方法来解决我的问题),它将.xlsx文件的每一行打印到csvwriter中。我调整了endrow()方法中的代码,将新行插入数据库,而不是写入csvwriter。还是有点慢,但我已经没有记忆问题了!

相关问题