Filling fields in Word using c# and Microsoft Word Interop

不想你离开。 提交于 2019-11-30 01:49:08

问题


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.


回答1:


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:


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


来源:https://stackoverflow.com/questions/18533198/filling-fields-in-word-using-c-sharp-and-microsoft-word-interop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!