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.
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.