Java读取word文档中的内容

Java读取word文档中的内容

一、效果:

1.1 doc文本

在这里插入图片描述

1.2 程序获取的内容

在这里插入图片描述

二、源码

2.1 pom文件

        <!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

2.2 Java代码

public class TestReadDoc {

    /**
     * 读取word文档中后缀为doc的文件
     * @param filePath
     * @return
     */
    public static String readWordDoc(String filePath){
        String content = null;
        InputStream input = null;
        try {
            input = new FileInputStream(new File(filePath));
            WordExtractor wex = new WordExtractor(input);
            content = wex.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
    
    /**
     * 读取word文档中后缀为docx的文件
     * @param filePath
     * @return
     */
    public static String readWordDocX(String filePath){
        String content = null;
        OPCPackage opcPackage = null;
        try {
            opcPackage = POIXMLDocument.openPackage(filePath);
            XWPFDocument xwpf = new XWPFDocument(opcPackage);
            POIXMLTextExtractor poiText = new XWPFWordExtractor(xwpf);
            content = poiText.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public static void main(String[] args) {
        System.out.println("****** 下面就是获取的内容 ******");
        
        String doc = "C:\\Users\\canwei\\Desktop\\test.doc";
        
        System.out.println(readWordDoc(doc));
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值