使用 c# 和 Microsoft Word Interop 在 Word 中填充字段 [英] Filling fields in Word using c# and Microsoft Word Interop

查看:49
本文介绍了使用 c# 和 Microsoft Word Interop 在 Word 中填充字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 C# Interop Assemblies 和以下代码在 Microsoft Word 中填写表单字段

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

string filename = @"N:mehlerVorlage2.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:mehlerAusgefuellt.docx");
doc.Close();
word.Quit();
System.Diagnostics.Process.Start(@"N:mehlerAusgefuellt.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 个文本表单域

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 from previous Versions")如果我将整个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆