3.0版本以前listener中拋出的所有異常都會被easyexcel捕獲,並且包裝成ExcelAnalysisException,寫法如下: private void parseXmlSource(InputStream inputStream, ContentHandler handler) { ...
3.0版本以前listener中拋出的所有異常都會被easyexcel捕獲,並且包裝成ExcelAnalysisException,寫法如下:
private void parseXmlSource(InputStream inputStream, ContentHandler handler) { InputSource inputSource = new InputSource(inputStream); try { SAXParserFactory saxFactory; String xlsxSAXParserFactoryName = xlsxReadContext.xlsxReadWorkbookHolder().getSaxParserFactoryName(); if (StringUtils.isEmpty(xlsxSAXParserFactoryName)) { saxFactory = SAXParserFactory.newInstance(); } else { saxFactory = SAXParserFactory.newInstance(xlsxSAXParserFactoryName, null); } saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(handler); xmlReader.parse(inputSource); inputStream.close(); } catch (ExcelAnalysisException e) { throw e; } catch (Exception e) { throw new ExcelAnalysisException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new ExcelAnalysisException("Can not close 'inputStream'!"); } } } }
3.1.5版本對此做了優化,只會包裝指定的異常,代碼如下:
private void parseXmlSource(InputStream inputStream, ContentHandler handler) { InputSource inputSource = new InputSource(inputStream); try { SAXParserFactory saxFactory; String xlsxSAXParserFactoryName = xlsxReadContext.xlsxReadWorkbookHolder().getSaxParserFactoryName(); if (StringUtils.isEmpty(xlsxSAXParserFactoryName)) { saxFactory = SAXParserFactory.newInstance(); } else { saxFactory = SAXParserFactory.newInstance(xlsxSAXParserFactoryName, null); } try { saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); } catch (Throwable ignore) {} try { saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); } catch (Throwable ignore) {} try { saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (Throwable ignore) {} SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(handler); xmlReader.parse(inputSource); inputStream.close(); } catch (IOException | ParserConfigurationException | SAXException e) { throw new ExcelAnalysisException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new ExcelAnalysisException("Can not close 'inputStream'!"); } } } }