使用邮件合并填充Microsoft Word文档

时间:2017-02-08 16:38:46

标签: c# ms-word interop ms-office

我想要以编程方式填充模板中的字段,但是当我尝试调试时找不到该字段。字段计数返回0.这是我的代码。

var application = new Application();
var document = new  Document();

document = application.Documents.Add(@"C:\Users\ISAAC B\Desktop\TECH HAVEN PROJECTS/template.docx");

application.Visible = true;

foreach (Field field in document.FormFields)
{
    if (field.Code.Text.Contains("Name"))
    {
        field.Select();
        application.Selection.TypeText("Tayo");
    }
}

document.SaveAs(@"C:\Users\ISAAC B\Desktop\TECH HAVEN PROJECTS/Project2017");

document.Close();
application.Quit();

1 个答案:

答案 0 :(得分:0)

        Object oMissing = System.Reflection.Missing.Value;
        Object oTrue = true;
        Object oFalse = false;
        Application oWord = new Application();
        Document oWordDoc = new Document();
      //  oWord.Visible = true;
        Object oTemplatePath = @"C:\Users\ISAAC B\Desktop\TECH HAVEN PROJECTS\Arup\template.docx";
        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        foreach (Field myMergeField in oWordDoc.Fields)
        {
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;
            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\", StringComparison.Ordinal);
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim();
                if (fieldName == "Name")
                {
                    myMergeField.Select();
                    oWord.Selection.TypeText("Tayo Isaac Bakare");
                }
            }
        }
        oWordDoc.SaveAs(@"C:\Users\ISAAC B\Desktop\TECH HAVEN PROJECTS\Arup\Project2017.docx");
        oWordDoc.Close();
        oWord.Quit();