Java保留原格式替换docx文档指定的key

本文展示了如何使用Java编程语言来保留原格式地替换docx文档中的特定关键字,包括详细的效果展示和代码示例。
摘要由CSDN通过智能技术生成

Java保留原格式替换docx文档指定的key

效果展示

在这里插入图片描述

代码demo

/**
 * 替换文档的占位符,保留占位符原有样式
 * 此处只用于demo,请根据业务需要,定制成你喜欢的样子
 */

public class DocxUtils {
   

    /**
     * 用一个docx文档作为模板,然后替换其中的内容,再写入目标文档中。
     *
     * @throws Exception
     */
    private static void templateWrite(String filePath, String outFilePath, Map<String, String> params) throws Exception {
   
        InputStream is = new FileInputStream(filePath);
        XWPFDocument doc = new XWPFDocument(is);
        Iterator<XWPFParagraph> paragraphsIterator = doc.getParagraphsIterator();
        while (paragraphsIterator.hasNext()) {
   
            //替换段落里面的变量
            replaceInPara(paragraphsIterator.next(), params);
        }
        OutputStream os = new FileOutputStream(outFilePath);
        doc.write(os);
        close(os);
        close(is);
    }

    private static XWPFDocument replaceTemplateKeyFromParams(String templatePath, Map<String, String> params) throws Exception {
   
        File tmpFile = ResourceUtils.getFile(templatePath);
        InputStream inputStream = new FileInputStream(templatePath);
        XWPFDocument xwpfDocument = new XWPFDocument(OPCPackage.open(tmpFile))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值