使用Java处理大型XLS文件的API /框架建议?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (27)

我需要技术选择来使用Java处理更大的XLS文件

  1. 它需要处理xmls文件,而不需要内存不足异常。
  2. 它需要对内存(工作内存)的使用进行优化。
提问于
用户回答回答于
    public void parseExcel(File file) throws IOException {

            OPCPackage container;
            try {
                container = OPCPackage.open(file.getAbsolutePath());
                ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
                XSSFReader xssfReader = new XSSFReader(container);
                StylesTable styles = xssfReader.getStylesTable();
                XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
                while (iter.hasNext()) {
                    InputStream stream = iter.next();

                    processSheet(styles, strings, stream);
                    stream.close();
                }
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (OpenXML4JException e) {
                e.printStackTrace();
            }

    }

    protected void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream) throws IOException, SAXException {

            InputSource sheetSource = new InputSource(sheetInputStream);
            SAXParserFactory saxFactory = SAXParserFactory.newInstance();
            try {
                SAXParser saxParser = saxFactory.newSAXParser();
                XMLReader sheetParser = saxParser.getXMLReader();
                ContentHandler handler = new XSSFSheetXMLHandler(styles, strings, new SheetContentsHandler() {

                @Override
                    public void startRow(int rowNum) {
                    }
                    @Override
                    public void endRow() {
                    }
                    @Override
                    public void cell(String cellReference, String formattedValue) {
                    }
                    @Override
                    public void headerFooter(String text, boolean isHeader, String tagName) {

                    }

                }, 
                false//means result instead of formula
                );
                sheetParser.setContentHandler(handler);
                sheetParser.parse(sheetSource);
            } catch (ParserConfigurationException e) {
                throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());


}

扫码关注云+社区

领取腾讯云代金券