Java 实现poi方式读取word文件内容

本文介绍了一个简单的Java程序,该程序能够从指定路径的 .doc/.docx 文件中读取文本内容。通过使用Apache POI库中的WordExtractor类,实现了对Microsoft Word文档的解析。

1、Maven Jar包

<!-- .docx -->

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>5.2.3</version>

</dependency>

<!-- .doc -->

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-scratchpad</artifactId>

<version>5.2.3</version>

</dependency>

2、Java代码

java 复制代码
package org.example.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class WordUtils {

    public String read(String path) {
        try  {
            if (path.toLowerCase().endsWith(".docx"))
                return readDocx(path);
            else if (path.toLowerCase().endsWith(".doc"))
                return readDoc(path);
            else
                throw new IllegalArgumentException("不支持的文件格式");
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public String readDocx(String path) throws IOException {
        try (InputStream in = new FileInputStream(path);
             XWPFDocument doc = new XWPFDocument(in)) {
            return new XWPFWordExtractor(doc).getText();
        }
    }
    public String readDoc(String path) throws IOException {
        try (InputStream in = new FileInputStream(path);
             HWPFDocument doc = new HWPFDocument(in)) {
            return new WordExtractor(doc).getText();
        }
    }

    public static void main(String[] args) {
        WordUtils wordUtils = new WordUtils();
        try {
            String docx = wordUtils.read("/Users/work/Documents/数据分析报告.doc");
            System.out.println(docx);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
相关推荐
果汁华3 小时前
java学习连续打卡30天(1)
java
武子康3 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
m0_639817153 小时前
基于springboot火锅店管理系统【带源码和文档】
java·spring boot·后端
怪兽20144 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang4 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志4 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友4 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者4 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
会编程的林俊杰4 小时前
SpringBoot项目启动时的依赖处理
java·spring boot·后端
一叶飘零_sweeeet4 小时前
深度拆解汽车制造系统设计:用 Java + 设计模式打造高扩展性品牌 - 车型动态生成架构
java·设计模式·工厂设计模式