C#向word文件书签处插值

本文介绍了一种使用C#编程语言,通过Microsoft Office Interop组件实现Word文档中书签值批量替换的方法。该方法首先创建Word应用程序实例,然后加载指定路径的模板文件并生成文档。遍历传入的书签字典,将书签位置的文本替换成对应值,最后保存并关闭文档。

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

Private void SetBookMarkValue(string filePath, Dictionary<string, string> bookMarks)
        {
            //创建一个Word应用程序实例
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;
            //模板文件地址

            object oTemplate = filePath;//模板路径
            //以模板为基础生成文档
            object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

            try
            {
                //赋值任意数据到书签的位置
                foreach (KeyValuePair<string, string> bookMark in bookMarks)
                {
                    oDoc.Bookmarks.get_Item(bookMark.Key).Range.Text = bookMark.Value;
                }

                oDoc.SaveAs(ref oTemplate, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
              oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

              oDoc = null;
              oWord = null;

            }
            catch(Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
            }
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值