java修改(增删查改)word指定文本内容

本文档介绍了一个使用Java处理Word文件的需求,通过深入研究Apache POI API,实现了对word文档的文本内容进行替换、增加、删除等操作。提供了pom文件配置、工具类代码和测试案例,帮助解决批量更新Word内容的问题。

        近期接到项目需求,对word文件内容进行批量更新。查遍某度未找到合适的解决方案,小众需求,没辙。只能顶着上,继续扣poi的api。虽然过程头大特么给头大开门,不过也算是解决了。

        该方法实现了对word文档中指定的文本内容进行替换,上增,下增,删除等操作。话不多说,代码如下:

pom文件:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
</dependency>

工具类:

import com.pcitc.common.constant.FileConstants;
import com.pcitc.common.exception.ServiceException;
import com.pcitc.common.utils.StringUtils;
import com.pcitc.common.utils.file.FileUtils;
import org.apache.poi.xwpf.usermodel.IRunElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @BelongsProject: stage3-cmis-itm
 * @BelongsPackage: 
 * @Author: zhousc
 * @CreateTime: 2023-02-15  14:45
 * @Description: 更新word工具类
 * @Version: 1.0
 */
public class UpdateWordUtil {

    private static final Logger log = LoggerFactory.getLogger(UpdateWordUtil.class);

    public static void main(String[] args) throws Exception {
        String filePath = "E:\\home\\建材订货合同.docx";
        File file = new File(filePath);
        MultipartFile multipartFile = FileUtils.fileToMultipartFile(file);
        String oldText = "根据《中华人民共和国民法典》及有关法律法规的规定,甲乙双方遵循平等自愿、协商一致和诚实信用的原则,现就建材订货等事宜签订合同如下:";
        // 上增
//        String newText1 = "这是上面的新内容!!!这是上面的新内容!!!这是上面的新内容!!!这是上面的新内容!!!这是上面的新内容!!!这是上面的新内容!!!这是上面的新内容!!!";
//        XWPFDocument xwpfDocument = updateWord(multipartFile, "up", oldText, newText1);

        // 下增
//        String newText0 = "这是下面的新内容!!!这是下面的新内容!!!这是下面的新内容!!!这是下面的新内容!!!这是下面的新内容!!!这是下面的新内容!!!这是下面的新内容!!!";
//        XWPFDocument xwpfDocument = updateWord(multipartFile,"down",oldText,newText0);

        // 替换
//        String newText2 = "这是替换的新内容!!!这是替换的新内容!!!这是替换的新内容!!!这是替换的新内容!!!这是替换的新内容!!!这是替换的新内容!!!这是替换的新内容!!!";
//        XWPFDocument xwpfDocument = updateWord(multipartFile, "replace", oldText, newText2);

        // 删除
        String newText2 = "";
        XWPFDocument xwpfDocument = updateWord(multipartFile, FileConstants.FILE_COORD_DELETE, oldText, newText2);

        // 输入到新文件
        FileOutputStream outStream = null;
        outStream = new FileOutputStream("E:\\home\\test1.docx");
        xwpfDocument.write(outStream);
        outStream.close();
    }

    /**
     * 修改word内容
     *
     * @param file    文件流
     * @param coord   基于要修改内容的坐标0:替換 1:上方 2:下方
     * @param oldText 要修改的原内容
     * @param newText 要修改的新内容
     * @throws IOException
     */
    public static XWPFDocument updateWord(MultipartFile file, String coord, String oldText, String newText) {
        XWPFDocument document = null;
        try {
            document = new XWPFDocument(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph xwpfParagraph : paragraphs) {
            String text = xwpfParagraph.getText();
            if (oldText.equals(text)) {
                List<XWPFRun> oldRuns = xwpfParagraph.getRuns();
                if (oldRuns.size() > 0) {
                    if (coord.equals(FileConstants.FILE_COORD_REPLACE)) {
                        Boolean aBoolean = removeOldText(oldRuns, xwpfParagraph,1);
                        // 存在替换内容,开始替换操作
                        if (StringUtils.isNotEmpty(newText)) {
                            if (aBoolean) {
                                // 留最后一条内容做替换处理
                                if (oldRuns.size() == 1) {
                                    XWPFRun newRun = oldRuns.get(0);
                                    // 根据下标替换新内容
                                    newRun.setText(newText, 0);
                                }
                            }
                        }

                    } else if (coord.equals(FileConstants.FILE_COORD_UP)) { // 上方加一条
                        List<IRunElement> iRuns = xwpfParagraph.getIRuns();
                        for (int i = 0; i < iRuns.size(); i++) {
                            if (i == 0) {
                                XWPFRun newRun = oldRuns.get(0);
                                String oldRunText = newRun.toString();
                                newRun.setText(newText, 0);
                                // 添加换行符
                                newRun.addCarriageReturn();
                                newRun.setText("    " + oldRunText);
                                break;
                            }
                        }

                    } else if (coord.equals(FileConstants.FILE_COORD_DOWN)) { // 下方加一条
                        List<IRunElement> iRuns = xwpfParagraph.getIRuns();
                        for (int i = 0; i < iRuns.size(); i++) {
                            int j = iRuns.size() - 1;
                            if (i == j) {
                                XWPFRun newRun = oldRuns.get(j);
                                // 添加换行符
                                newRun.addCarriageReturn();
                                newRun.setText("    " + newText);
                            }
                            continue;
                        }
                    } else if (coord.equals(FileConstants.FILE_COORD_DELETE)) { // 删除当前条款
                        Boolean aBoolean = removeOldText(oldRuns, xwpfParagraph,0);
                        if (!aBoolean) {
                            throw new ServiceException("删除条款出错!!!");
                        }
                    }
                }
            }
        }
        log.info(" ========== ========== 更新完成!!! ========== ========== ");
        return document;
    }


    /**
     * 遍历删除原内容
     *
     * @param oldRuns
     * @param xwpfParagraph
     * @param n   长度 - n
     * @return
     */
    private static Boolean removeOldText(List<XWPFRun> oldRuns, XWPFParagraph xwpfParagraph,Integer n) {
        Boolean aBoolean = false;
        // 留一个做内容替换
        for (int i = 0; i < oldRuns.size() - n; i++) {
            xwpfParagraph.removeRun(i);
        }
        if (oldRuns.size() == n) {
            aBoolean = true;
        } else {
            aBoolean = removeOldText(oldRuns, xwpfParagraph,n);
        }
        return aBoolean;
    }
}

测试:

public void updateTest(MultipartFile file, String coord, String oldText, String newText,String writeUrl) throws IOException {
        XWPFDocument xwpfDocument = UpdateWordUtil.updateWord(file, coord, oldText, newText);
        if (ObjectUtils.isNotEmpty(xwpfDocument)) {
            // 输入到新文件
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(writeUrl);
            xwpfDocument.write(outStream);
            outStream.close();
        }
    }

        就酱,完美解决问题!感觉有帮助的小伙伴欢迎点赞关注,O(∩_∩)O哈哈~

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值