2017-02-08 7 views
0

私はプログラムで塗りつぶしたいテンプレートにフィールドを持っていますが、デバッグしようとしたときにフィールドが見つかりませんでした。フィールドカウントは0を返します。これは私のコードです。差し込み印刷でMicrosoftワード文書を記入

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アプリケーションの文書(またはテンプレート)を見てください。フォームフィールドをダブルクリックすると、フィールドのオプションを含むダイアログボックスが表示されます。これらのオプションの1つは、フィールドの名前です。あなたは、(保護された!)ドキュメントの任意のフォームフィールドをアドレス指定し、document.FormFields( "theName")を使用してそれに書き込むことができます。Result = "Tayo" –

+0

ありがとう@CindyMeister。差し込み印刷をしたいですか?私が欲しかったのは、プログラムで単語文書に書き込むことです。 –

+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(); 
関連する問題