How to interrupt POI streaming reader after readin

2019-09-18 18:14发布

问题:

I need to find a way to interrupt the stream reader (reading XML and parsing it with SAX) after first line. Meaning after I read the column names.

Any idea how to do that?

CODE:

    XSSFSheetXMLHandler.SheetContentsHandler mySheetContentsHandler = new MySheetContentsHandler(true, xlsxHeaders);
    File myFile = new File(filePath);
    OPCPackage pkg = OPCPackage.open(myFile.getPath());
    XSSFReader reader = new XSSFReader(pkg);
    StylesTable styles = reader.getStylesTable();
    ReadOnlySharedStringsTable sharedStrings = new ReadOnlySharedStringsTable(pkg);
    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStrings, mySheetContentsHandler, true);

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(handler);
    parser.parse(new InputSource(reader.getSheetsData().next())); 

As you may see here, XSSFSheetXMLHandler.SheetContentsHandler is an interface with 4 methods. But how may I interrupt the reading of the file?

I have tried to do handler.endDocument(); which has executed in the implemented method of the interface endRow();, it didn't help, program went to another row without any interruption.

回答1:

A vague idea:

How about extend XSSFSheetXMLHandler, have a method "iterrupt" that sets some flag to true. And override start/endElement, start/endDocument. All you can do is something like below e.g

@Override
public void startElement(java.lang.String uri, java.lang.String localName, java.lang.String name, org.xml.sax.Attributes attributes) 
{
 if(interrupted)
 {
   //throw your custom exception;
 }
 super.startElement(uri,localName,name,attributes);

}

or in your class MySheetContentsHandler you can introduce the method, and then in cell(...) or endRow you can check the interrupt state before processing? Similarly you can override other methods. Worth a try?



标签: java excel xssf