开发者

Replace MergeFields in a Word 2003 document and keep style

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 appli开发者_如何转开发ed 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜