Einfügen eines Feldes in Word mit C#
Frank Dzaebel, erstellt am: 30.10.2005, zuletzt geändert: 17.05.2005
Kategorie: Office, .NET-Version: 1.1, [Download]

Felder sind unter Microsoft Word® eine flexible Lösung um variable Inhalte anzuzeigen und zu synchronisieren. Eine Automation über C# bietet sich deswegen des öfteren an. Hier für Word® 2003.

// Fuer Word 2003. Verweis "Microsoft Word 11.0 Object Library"
using System.Windows.Forms;
using Word=Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;

// [...] 

/// <summary>Newline-Zeichen des Betriebssystems</summary> 
string NL = Environment.NewLine; 

private void Form1_Load(object sender, System.EventArgs e)
{
  Word.ApplicationClass wordapp = new Word.ApplicationClass(); 
  object n = Missing.Value; 
  object docName = Application.StartupPath + "\\mydoc.doc"; 
  if (wordapp == null || !File.Exists((string)docName)) 
  {
    MessageBox.Show("Keine Verbindung zu Word herstellbar!"+NL+
      "Datei: "+(string)docName); return; 
  } 
  wordapp.Visible = true; 
  try 
  {
    wordapp.Documents.Open(ref docName, ref n, ref n, ref n, ref n, ref n, 
     ref n, ref n, ref n, ref n, ref n, ref n, ref n, ref n, ref n, ref n); 
    Word.Document  doc = wordapp.ActiveDocument;
    Word.Selection sel = wordapp.Selection;
    object fieldType = Word.WdFieldType.wdFieldEmpty;
    object text = "MyText1"; // "DOCPROPERTY MyText1"
    object preserve = false; // true
    doc.Fields.Add(sel.Range, ref fieldType, ref text, ref preserve);
  } 
  catch (Exception ex) 
  {
    MessageBox.Show(ex.Message);   
  }     
}