在Word 2003文档替换MERGEFIELDS,并保持风格 [英] Replace MergeFields in a Word 2003 document and keep style

查看:1870
本文介绍了在Word 2003文档替换MERGEFIELDS,并保持风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图建立一个库,以取代Word 2003文档的MERGEFIELDS,一切工作正常,但我失去申请到外地当我更换了风格,是有办法养吗?

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

我使用的选择CopyFormat和PasteFormat方法,也使用get_style和set_style但没有exent尝试。

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

推荐答案

而不是使用的TypeText在您选择的顶部使用字段的Result属性的:

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.

这篇关于在Word 2003文档替换MERGEFIELDS,并保持风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆