使用C#和Microsoft Word Interop填充Word中的字段 [英] Filling fields in Word using c# and Microsoft Word Interop
问题描述
我尝试使用带有以下代码的C#互操作程序集在Microsoft Word中填写表单字段
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无法打开文件Ausgefuellt.docx,并显示一条消息,指出发生了未知错误.
Microsoft Word can not open the File Ausgefuellt.docx and Shows a Message saying that an unknown Error has occured.
我创建了一个简单的Word文档,其中包含一些未格式化的文本和2个Text-Form-Fields
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
我设法指定了问题.我创建了一个仅包含一个文本表单字段的文档. 在Word 2013中,可以在主题"Formulare aus Vorversionen"下找到它(我将其翻译为以前版本的Formfields") 如果我注释掉整个foreach块,以便仅打开并保存文档,我将得到相同的结果.
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.
如果我直接在Word中打开源文件,那是没有问题的.我还尝试加载文档并使Word可见.结果看起来像一个空的Word实例,没有加载文档.
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.
推荐答案
您应使用:
doc = Word.Documents.Add(filename);
代替:
doc = Word.Documents.Open(filename);
因此,Word将使用模板创建文档文件,而不打开模板本身. 当活动文档是模板时,Word的行为似乎有所不同.
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.
这篇关于使用C#和Microsoft Word Interop填充Word中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!