java 笔记: 读取 doc/docx 中文本
2018-10-11 本文已影响244人
silencefun
场景:因要处理大量行业数据每个(大部分)单个项目文件中包含一份文档说明部分是txt,另外大部分是doc/docx.
通过 百度得到需要poi方式 读取。
大体是参考此处博主文章:
https://blog.csdn.net/qq_36243824/article/details/71643193
1.下载配置poi的jar。
地址 http://poi.apache.org/download.html 目前最新release 版本是4.0
下载后解压,如图:

2.编写代码
把这6个poi开头的jar 包导入新建的测试空项目,写如下代码:
public static String getPhoneNum(File filePath) {
String text = "";
String fileName = filePath.getName().toLowerCase();// 得到名字小写
try {
FileInputStream in = new FileInputStream(filePath);
if (fileName.endsWith(".doc")) { // doc为后缀的
WordExtractor extractor = new WordExtractor(in);
text = extractor.getText();
}
if (fileName.endsWith(".docx")) { // docx为后缀的
XWPFWordExtractor docx = new XWPFWordExtractor(new XWPFDocument(in));
text = docx.getText();
}
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
public static void main(String[] args) throws Exception {
File f = new File("E:\\06.doc");
System.out.println(getPhoneNum(f));
}
但是 提示 位于
XWPFWordExtractor docx = new XWPFWordExtractor(new XWPFDocument(in));
有错误:
The type org.apache.xmlbeans.XmlException cannot be resolved. It is indirectly referenced from required .class files
参考了https://stackoverflow.com/questions/23080945/java-lang-classnotfoundexception-org-apache-xmlbeans-xmlexception
的回答,又仔细看了原博主的做法,需要把 下载解压后的ooxm-lib下的jar包加进去。

运行 仍然报错,如图

主要是:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.bidimap.TreeBidiMap
显然是缺少引用,回到下载的poi的jar包,路径中有lib,打开如图:

3.测试
导入 collections4那个,应用,
测试doc文档,成功打印出

文档内是

测试docx文档,

出错,如图

显然还是缺少包的引用:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.compress.archivers.zip.ZipFile
查找后到下载地址http://commons.apache.org/proper/commons-compress/download_compress.cgi
当前最新版本是1.1.8版本,下载解压后:

把第一个jar包配置到项目里,再次执行,成功运行,
