Replace MergeFields in a Word 2003 document and keep the style

I am trying to create a library to replace MergeFields in a Word 2003 document, everything works fine, except that I lose the style applied to the field when I replace it, is there any way to save it?

This is the code I use 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 get_style and set_style, but without exent.

+3
source share
1 answer

Instead of using TypeText at the top of your selection, use the Result property for the field:

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

This will ensure that any formatting is saved in the field.

+6
source

Source: https://habr.com/ru/post/1719390/


All Articles