Java poi之word文本替换

文章介绍了如何利用ApachePOI库在Java中实现Word文档的文本内容替换功能。通过添加Maven依赖,作者提供了代码示例,展示如何读取DOC和DOCX格式的文档,以及如何进行文本替换并保存新文件。文章还展示了替换前后的效果对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在这里插入图片描述

应公司需求,需实现以下功能

  1. word文本内容的替换;
  2. word文本内容的提取
  3. word文档中图片的提取存放

此文章将使用Apache POI实现Word文档中文本内容的替换更新;

Apache POI 是基于 Office Open XML 标准(OOXML)和 Microsoft 的 OLE 2 复合文档格式(OLE2)处理各种文件格式的开源项目。 简而言之,您可以使用 Java 读写 MS Excel 文件,可以使用 Java 读写 MS Word 和 MS PowerPoint 文件。

  • HSSF - 提供读写 Microsoft Excel XLS 格式 (Microsoft Excel 97 (-2003)) 档案的功能。
  • XSSF - 提供读写 Microsoft Excel OOXML XLSX 格式 (Microsoft Excel XML (2007+)) 档案的功能。
  • SXSSF - 提供低内存占用量读写 Microsoft Excel OOXML XLSX 格式档案的功能。
  • HWPF - 提供读写 Microsoft Word DOC97 格式 (Microsoft Word 97 (-2003)) 档案的功能。
  • XWPF - 提供读写 Microsoft Word DOC2003 格式 (WordprocessingML (2007+)) 档案的功能。
  • HSLF/XSLF - 提供读写 Microsoft PowerPoint 格式档案的功能。
  • HDGF/XDGF - 提供读 Microsoft Visio 格式档案的功能。
  • HPBF - 提供读 Microsoft Publisher 格式档案的功能。
  • HSMF - 提供读 Microsoft Outlook 格式档案的功能。

文档准备

小编准备了以下两个文档:《孤勇者.doc》《青鸟.docx》,分别代表不同版本的文档,里边分别记录了各自的歌词,挑选其中个别词语进行替换测试,测试目标已用红蓝颜色标注,以便验证替换结果,如下图
在这里插入图片描述

引入Maven依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

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

代码块

package com.bjzaxk.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
//        String filePath = "C:\\Users\\Administrator\\Desktop\\java_poi\\demo_file\\孤勇者.doc";
//        String formart = "DOC";
        String filePath = "C:\\Users\\Administrator\\Desktop\\java_poi\\demo_file\\青鸟.docx";
        String formart = "DOCX";
        Map<String, String> textMap = new HashMap<>();
        textMap.put("蔚蓝的", "湛蓝的");
        textMap.put("振翅高飞", "翱翔天际");
//        textMap.put("他们说", "They sey");
//        textMap.put("爱你", "Love you");
        wordTextSubstitution(filePath, formart, textMap);
    }

    /**
     * @param filePath 替换文件所在路径
     * @param formart  替换文件扩展名
     * @param map      替换数据集合
     * @description: 替换word中的文字
     * @author: Mr.Jkx
     * @time: 2023/1/10 13:19
     */
    public static void wordTextSubstitution(String filePath, String formart, Map<String, String> map) {
        String textPath = "";
        File file = new File(filePath);
        String fileName = file.getName();
        try {
            if ("DOCX".equals(formart)) {
                if (fileName != null && fileName != "") {
                    String name = fileName.substring(0, fileName.length() - 5);
                    textPath = filePath.replaceAll(fileName, name + "_" + System.currentTimeMillis() + ".docx");
                }
                XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(filePath));
                // 替换段落中的指定文字
                Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();

                while (itPara.hasNext()) {
                    XWPFParagraph paragraph = itPara.next();
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (int i = 0; i < runs.size(); i++) {
                        String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
                        if (oneparaString != null) {
                            for (Map.Entry<String, String> entry : map.entrySet()) {
                                oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
                            }
                            runs.get(i).setText(oneparaString, 0);
                        }
                    }
                }

                // 创建新文件存放新内容
                FileOutputStream outStream = new FileOutputStream(textPath);
                document.write(outStream);
                outStream.close();
                System.out.println("--- SUCCESS!");
            } else if ("DOC".equals(formart)) {
                if (fileName != null && fileName != "") {
                    String name = fileName.substring(0, fileName.length() - 4);
                    textPath = filePath.replaceAll(fileName, name + "_" + System.currentTimeMillis() + ".doc");
                }
                HWPFDocument document = new HWPFDocument(new FileInputStream(filePath));
                Range range = document.getRange();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    range.replaceText(entry.getKey(), entry.getValue());
                }
                // 创建新文件存放新内容
                FileOutputStream outStream = new FileOutputStream(textPath);
                document.write(outStream);
                outStream.close();
                System.out.println("--- SUCCESS!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

替换结果验证

孤勇者替换结果对比

在这里插入图片描述

青鸟替换结果对比

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值