2017-02-08 83 views
0

我在模板中有一個字段,我想以編程方式填充,但是當我嘗試調試時沒有找到該字段。字段計數返回0.這是我的代碼。用Mail合併填充Microsoft word文檔

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(); 
+0

你似乎是使用表單域,而不是郵件合併(具體技術在Word),所以我相應更正標題。查看Word應用程序中的文檔(或模板);雙擊表單字段,您應該得到一個對話框,其中包含該字段的選項。其中一個選項是該字段的名稱。你可以在(protected!)文件中的任何表單域中寫入數據,並使用document.FormFields(「theName」)寫入。Result =「Tayo」 –

+0

謝謝@CindyMeister。請我想使用郵件合併。因爲我想要的是以編程方式寫入Word文檔 –

+0

我想我找到了一個解決方案。所以我可以輸入數據並將其保存到Word文檔中 –

回答

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();