POI 是否提供 Event-Driven API 来读取 XLS 和 XLSX 文件?

Does POI provide an Event-Driven API to read XLS and XLSX Files?

希望标题说明了一切。我知道较新的 'SS' 模型同时支持 XLS 和 XLSX 格式文件,但据我所知,它似乎没有 event-driven 实现:-(

我只想读文件,不想写文件,我只需要单元格内容和它们的数据类型。

是的,在 Apache POI 中可以使用事件驱动阅读:

请看这个link:how-to-event-reading

As stated: org.apache.poi.poifs.eventfilesystem.POIFSReaderListener is an interface used to register for documents. When a matching document is read by the org.apache.poi.poifs.eventfilesystem.POIFSReader, the POIFSReaderListener instance receives an org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent instance, which contains an open DocumentInputStream and information about the document.

您的入门指南:

public static void main(final String[] args) throws IOException
{
    final String filename = args[0];
    POIFSReader r = new POIFSReader();
    r.registerListener(new MyPOIFSReaderListener());
    r.read(new FileInputStream(filename));
}

static class MyPOIFSReaderListener implements POIFSReaderListener
{
    public void processPOIFSReaderEvent(final POIFSReaderEvent event)
    {
        final POIFSDocumentPath path = event.getPath();
        final String name = event.getName();
        final DocumentInputStream stream = event.getStream();
    }
}

是,也不是!

Apache POI 确实提供了以流式、低内存、事件驱动的方式读取两种 Excel 文件格式的方法

但是...因为这两种文件格式的存储方式非常不同(一种是 XML 的位保存在 zip 文件中,另一种是二进制记录),无法读取两种格式都以事件方式使用相同的代码。

因此,您的选择是购买更多内存 + 使用通过提供通用接口隐藏差异的 UserModel 方法,或者编写两批事件代码来处理两种不同的格式

对于 XLS 文件/HSSF,您应该遵循 Apache POI docs on the HSSF Event API

对于 XLSX 文件/XSSF,您应该遵循 Apache POI docs on the XSSF SAX Event API

可以在 Apache POI 源代码和示例中找到这两种应用的各种示例。