用C#填充Word模板字段 [英] Filling Word template fields with C#

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

问题描述

当前,如果我创建带有字段的Word文档模板,然后使用C#填充它们,我将执行类似此操作...

Currently, if I create a Word Document Template with fields, and then fill them using C#, I do it similar to this...

object missing = Type.Missing;
Word.Application app = new Word.Application();
Word.Document doc = app.Documents.Open("file.doc", ref missing, true);
Word.FormFields fields = doc.FormFields;
fields[2].Result = "foo"
fields[3].Result = "bar"

有没有更好的方法来引用这些字段?

Is there a better way to reference the fields?

我注意到在创建模板时,我可以在字段中添加标题和标签,但是我还没有找到引用这些属性的方法.能够命名字段并直接引用它们,而不是仅仅计算并弄清楚我在哪个字段上,这将是很好的选择.

I notice when creating the template I can add a Title and a Tag to the field, but I haven't found a way to reference those properties. It would be nice to be able to name fields and reference them directly, instead of just counting and figuring out which field I am on.

推荐答案

您是否正在使用旧版表单?当您将旧版表单字段添加到Word文档时,在属性">字段设置"下会出现一个书签",它基本上就是该字段的名称.默认情况下,旧文本字段的书签将为"Text1","Text2"等.

Are you using legacy forms? When you add a legacy form field to a Word doc, under Properties > Field Settings there is a Bookmark which is basically the name of the field. By default, a legacy text field will have a Bookmark of "Text1", "Text2", etc.

因此在VBA中:

ActiveDocument.FormFields("Text1").Result = "asdf"

在您的情况下,可能是(C#):

In your case it might be (C#):

doc.FormFields["Text1"].Result = "asdf"

或者您可以简单地编写一个循环,以扫描字段列表并查找给定名称(pseudo-VB):

Or you could simply write a loop that scans the list of fields and looks for a given name (pseudo-VB):

Function GetFieldByName(name As String) As Field
    Dim i
    For i = 0 to fields.count - 1
        If fields(i).Name = name Then Return fields(i)
    Next
    Return Nothing
End Function

如果您正在使用较新的表单字段控件,则可以在其中设置标签并使用VSTO(C#)自动进行操作:

If you're using the newer form field controls where you can set a Tag and automate with VSTO (C#):

doc.SelectContentControlsByTag("Address")[1].Range.Text = "asdf"

此处了解更多信息.

这篇关于用C#填充Word模板字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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