Java读取word文件 No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
有个项目涉及到了操作word文档,当把一份未加密word文档放在项目resources目录下进行临时开发,读取这个word时报错:
Caused by: org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file

从字面意思可以知道:读取的不是一份有效的文件。先查看测试用的word文档原件:

编译后的word文档打开有损坏提示,打开以后文件乱码:


这是异常提示读取的不是一个有效文件的原因
解决方法:
在项目的pom.xml文件里新增一个编译规则:
<build>
<plugins>
...
<!-- 过滤掉不需要编译的文件, 还可以是doc、xlsx、txt 等等-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>docx</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
...
</plugins>
</build>
再执行代码word文档就读取正常了。
当然,如果是word模板填充,还可以考虑将word模板换成html,使用Freemarker语法填充Html,还节省了读取文件的IO消耗
Freemarker语法填充Html:https://www.cnblogs.com/anyuan/p/15421548.html

浙公网安备 33010602011771号