Replace MergeFields in a Word 2003 document and keep style

帅比萌擦擦* 提交于 2019-12-10 09:02:25

问题


I've been trying to create a library to replace the MergeFields on a Word 2003 document, everything works fine, except that I lose the style applied to the field when I replace it, is there a way to keep it?

This is the code I'm using to replace the fields:

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
    }
}

I tried using the CopyFormat and PasteFormat methods in the selection, also using the get_style and set_style but to no exent.


回答1:


Instead of using TypeText over the top of your selection use the the Result property of the Field:

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

This will ensure any formatting in the field is retained.



来源:https://stackoverflow.com/questions/1525808/replace-mergefields-in-a-word-2003-document-and-keep-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!