开发者社区> 问答> 正文

POI SAX 如何修改大excel 文件内容

我现在要解析一个大的excel文件,直接用POI的方式会OOM,现在用POI SAX(事件驱动模式)问题解决了。
但是现在处理完数据需要每行返回一个状态,添加到行末尾,其他数据格式保持原样。这个请问怎么处理?

展开
收起
蛮大人123 2016-06-06 15:32:38 4084 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    首先先去http://poi.apache.org/faq.html :这个是个常用的问题列表,在

    1. I think POI is using too much memory! What can I do?

    This one comes up quite a lot, but often the reason isn't what you might initially think. So, the first thing to check is - what's the source of the problem? Your file? Your code? Your environment? Or Apache POI?

    Next, use the example program ToCSV to try reading the a file in with HSSF or XSSF. Related is XLSX2CSV, which uses SAX parsing for .xlsx

    我们看到了POI已经提出了针对这个问题的回答,而且正好在XLS2CSV中找到了很好的解决读取大容量的方法.
    在XLS2CSV中,即使是读取300M的2007excel文件也没有什么问题,占用的内存也是可以接受的。

    在这段代码中的注释中写出了下面一段话:
    

    *Data sheets are read using a SAX parser to keep the

    • memory footprint relatively small, so this should be
    • able to read enormous workbooks. The styles table and
    • the shared-string table must be kept in memory. The
    • standard POI styles table class is used, but a custom
    • (read-only) class is used for the shared string table
    • because the standard POI SharedStringsTable grows
    • very quickly with the number of unique strings.

    大概的意思就是说通用的处理方法会快速消耗掉内存,所以采用了 SAX parser方法来处理大容量的文件.

          public void processSheet( 
                StylesTable styles, 
                ReadOnlySharedStringsTable strings, 
                InputStream sheetInputStream) 
                throws IOException, ParserConfigurationException, SAXException { 
    
            InputSource sheetSource = new InputSource(sheetInputStream); 
            SAXParserFactory saxFactory = SAXParserFactory.newInstance(); 
            SAXParser saxParser = saxFactory.newSAXParser(); 
            XMLReader sheetParser = saxParser.getXMLReader(); 
            ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output); 
            sheetParser.setContentHandler(handler); 
            sheetParser.parse(sheetSource); 
        } 
    上面的一段代码是比较核心的代码,通过SAXParser解析xml文件,尽量不占用内存资源,从而达到读取大文件的目的。

    XLSX2CSV代码下载: http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java

    2019-07-17 19:28:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多