c# - 替换 Word 2003 文档中的 MergeFields 并保持样式

标签 c# interop ms-word vsto mergefield

我一直在尝试创建一个库来替换 Word 2003 文档中的 MergeFields,一切正常,只是在替换它时丢失了应用于该字段的样式,有没有办法保留它?

这是我用来替换字段的代码:

private void FillFields2003(string template, Dictionary<string, string> values)
{
    object missing = Missing.Value;
    var application = new ApplicationClass();
    var document = new Microsoft.Office.Interop.Word.Document();

    try
    {
        // Open the file

        foreach (Field mergeField in document.Fields)
        {
            if (mergeField.Type == WdFieldType.wdFieldMergeField)
            {
                string fieldText = mergeField.Code.Text;
                string fieldName = Extensions.GetFieldName(fieldText);

                if (values.ContainsKey(fieldName))
                {
                    mergeField.Select();
                    application.Selection.TypeText(values[fieldName]);
                }
            }
        }
        document.Save();
    }
    finally
    {
        // Release resources
    }
}

我尝试在选择中使用 CopyFormat 和 PasteFormat 方法,也尝试使用 get_style 和 set_style 但没有用到任何程度。

最佳答案

不要在选择的顶部使用 TypeText,而是使用 Field 的 Result 属性:

          if (values.ContainsKey(fieldName))
          {
             mergeField.Result = (values[fieldName]);
          }

这将确保保留字段中的所有格式。

关于c# - 替换 Word 2003 文档中的 MergeFields 并保持样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1525808/

相关文章:

r - 从 R 中以 Word 格式将数据导出到表格

vba - 从 Excel 打开 Word 文档并将内容粘贴到 Outlook 邮件正文

c# - Xamarin Forms - 自定义渲染器无法获取 native 控件 (UWP)

c# - 在C#中单击鼠标获取鼠标坐标

c# - 互操作和 CRL 事件

java - 将图片放入word文档中

c# - 如何从 .NET 将文件上传到一个驱动器

c# - 系统.InvalidOperationException : 'A method was called at an unexpected time when calling LaunchUriAsync inside ToastNotification UWP

ms-word - COMException:调用的对象已与其客户端断开连接

c# - 在同一解决方案中使用 VB.NET 和 C#