12
votes

I tried to Fill out Form Fields in Microsoft Word using C# Interop Assemblies with the following Code

string filename = @"N:\mehler\Vorlage2.dotx";

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

doc = word.Documents.Open(filename);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.FormField field in doc.FormFields)
{
    switch (field.Name)
    {
        case "Text2":
            field.Range.Text = "1";
            break;

        default:
            break;
    }
}

doc.SaveAs2(@"N:\mehler\Ausgefuellt.docx");
doc.Close();
word.Quit();
System.Diagnostics.Process.Start(@"N:\mehler\Ausgefuellt.docx");

Microsoft Word can not open the File Ausgefuellt.docx and Shows a Message saying that an unknown Error has occured.

I created a simple Word Document with a bit of unformated text and 2 Text-Form-Fields

can anyone tell me, what went wrong or if ia have an Error in my Source Code

Edit: I managed to specify the Problem. I created an Document only conaining one Text Form Field. In Word 2013 this is found unter the Topic "Formulare aus Vorversionen" (I would translate this to "Formfields from former Versions") If I comment out the whole foreach Block so that I would only open and save the Document, I get the same result.

If I open the Source File directly in Word it is no Problem. I also tried to load the Document and make Word Visible. The Result looked like an empty Word instance with no Document loaded.

2
the execution breaks at open method?Kazimierz Jawor
I also found this Topic stackoverflow.com/q/17383430/1307426 may it be an Word Interop Problem?sebastianmehler
Why are you trying to update the template? Maybe you should issue a Word.Documents.Add(filename); so Word will create a new document based on your template...Nir Kornfeld
@Nir Kornfeld: Nice "Word.Documents.Add(filename) did the Trick. Using this instead of Word.Document.Open(filename) Word does not Crash. BTW: field.Range.Text removed the Textfield and replaces it with the given Text, but setting field.Result does the Trick...sebastianmehler
@sebastianmehler - I will write my solution as an answer. Can you please mark it as accepted?Nir Kornfeld

2 Answers

15
votes

You should use:

doc = Word.Documents.Add(filename);

Instead of:

doc = Word.Documents.Open(filename);

So Word will use the template to create a document file, and not open the template itself. It seems Word behaves differently when the active document is a Template.

2
votes

Use that, it should work:

Word.Application WordApp;
Word.Document WordDoc;

object misValue = System.Reflection.Missing.Value;

WordApp = new Word.ApplicationClass();
WordDoc = WordApp.Documents.Open(filePath2, misValue, misValue, misValue, misValue, misValue,
        misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
WordDoc.Activate();