异常:java.lang.IllegalArgumentException: The document is really a OOXML file

异常:java.lang.IllegalArgumentException: The document is really a OOXML file

1、场景

项目中需要使用到读取 word 文档中的内容,使用的工具是 apache poi 来实现 word 、ppt 、excel 等文件的读取。在开发过程中,读取文件的过程中,出现了异常: java.lang.IllegalArgumentException: The document is really a OOXML file


2、分析

office中,word 文档的保存是有 doc(office 2003-2007) 和 docx 两种格式的。在 apche poi 中,对 不同格式的 word 文档是不同类进行支持的。

图示中使用的是 HWPFDocument 类读取 docx 格式的文档,而 HWPFDocument 是只支持 doc 格式的文档的读取,所以会报错。

错误示例:


3、doc 和 docx 文档读取详解

现在对读取两种格式的文档,做正确的示例代码详解:

读取doc

// 使用 HWPFDocument 类读取 doc 格式文档

// --------- doc -----------
File file = new File("E:\\search-file\\22.doc");
FileInputStream fis = null;
HWPFDocument document = null;
WordExtractor extractor = null;
try {
    fis = new FileInputStream(file);
    document = new HWPFDocument(fis);
    extractor = new WordExtractor(document);
    log.info("extractor.getText:{}", extractor.getText());
} catch (Exception e) {
    e.printStackTrace();
}

格式使用错误就会报错:java.lang.IllegalArgumentException: The document is really a OOXML file

读取 docx

// 使用 XWPFDocument 类读取 docx 格式的文档

// --------- docx -----------
File file = new File("E:\\search-file\\11.docx");
FileInputStream fis = null;
XWPFDocument document = null;
XWPFWordExtractor extractor = null;
try {
    fis = new FileInputStream(file);
    document = new XWPFDocument(fis);
    extractor = new XWPFWordExtractor(document);
    log.info("extractor.getText:{}", extractor.getText());
} catch (Exception e) {
    e.printStackTrace();
}

XWPFDocument 类读取 doc 格式文档使用错误会报错:org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)

4、总结

apache poi 工具还是很强大的,功能非常多,对具体使用也可参考 apache poi 的官方文档:

https://poi.apache.org/apidocs/index.html

请注意自己使用的 apache poi 的版本,参考对应版本的 javadocs

posted @   向宁的光  阅读(3680)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示