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

}
相关推荐
干了这杯柠檬多5 分钟前
使用maven-shade-plugin解决es跨版本冲突
java·elasticsearch·maven
Proxbj12 分钟前
MQTT解析
java
q5673152313 分钟前
C语言编写轻量爬虫工具
c语言·开发语言·爬虫
啊阿狸不会拉杆20 分钟前
《算法导论》第 4 章 - 分治策略
开发语言·数据结构·c++·算法·排序算法
神洛华30 分钟前
Lua语言程序设计1:基础知识、数值、字符串与表
开发语言·lua
埃泽漫笔33 分钟前
Spring 的 ioc 控制反转
java·spring·ioc
太阳之神aboluo37 分钟前
SpringCloud (4) 分布式事务
java·spring·spring cloud
Noii.1 小时前
Mybatis的应用及部分特性
java·数据库·mybatis
不像程序员的程序媛1 小时前
java下载word
word