美文网首页
java 笔记: 读取 doc/docx 中文本

java 笔记: 读取 doc/docx 中文本

作者: silencefun | 来源:发表于2018-10-11 18:24 被阅读244次

    场景:因要处理大量行业数据每个(大部分)单个项目文件中包含一份文档说明部分是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

    下载后解压,如图:

    image.png

    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包加进去。

    image.png

    运行 仍然报错,如图

    image.png

    主要是:

    Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.bidimap.TreeBidiMap
    

    显然是缺少引用,回到下载的poi的jar包,路径中有lib,打开如图:

    image.png

    3.测试

    导入 collections4那个,应用,

    测试doc文档,成功打印出

    image.png

    文档内是


    image.png

    测试docx文档,

    image.png

    出错,如图

    image.png

    显然还是缺少包的引用:

         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版本,下载解压后:

    image.png

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


    image.png

    相关文章

      网友评论

          本文标题:java 笔记: 读取 doc/docx 中文本

          本文链接:https://www.haomeiwen.com/subject/tyxiaftx.html