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);
        }
    }

}
相关推荐
xiaoxue..9 小时前
合并两个升序链表 与 合并k个升序链表
java·javascript·数据结构·链表·面试
JQLvopkk9 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#
忧郁的Mr.Li9 小时前
SpringBoot中实现多数据源配置
java·spring boot·后端
玄同7659 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
czy87874759 小时前
深入了解 C++ 中的 `std::bind` 函数
开发语言·c++
消失的旧时光-19439 小时前
从 Kotlin 到 Dart:为什么 sealed 是处理「多种返回结果」的最佳方式?
android·开发语言·flutter·架构·kotlin·sealed
yq1982043011569 小时前
静思书屋:基于Java Web技术栈构建高性能图书信息平台实践
java·开发语言·前端
一个public的class9 小时前
你在浏览器输入一个网址,到底发生了什么?
java·开发语言·javascript
有位神秘人9 小时前
kotlin与Java中的单例模式总结
java·单例模式·kotlin
Jinkxs9 小时前
Gradle - 与Groovy/Kotlin DSL对比 构建脚本语言选择指南
android·开发语言·kotlin