Filling Word template fields with C#

谁都会走 提交于 2019-12-05 16:09:36

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.

So in VBA:

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

In your case it might be (C#):

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

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

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"

Read more about Content Controls here.

One good way to do it is to, at each place in the template you would like to add text later, place a bookmark (Insert -> Links -> Bookmark). To use them from your code, you would access each bookmark by its name, see this example:

Word._Application wApp = new Word.Application();
Word.Documents wDocs = wApp.Documents;
Word._Document wDoc = wDocs.Open(ref "file_path_here", ReadOnly:false);
wDoc.Activate();

Word.Bookmarks wBookmarks = wDoc.Bookmarks;
Word.Bookmark wBookmark = wBookmarks["Bookmark_name"];
Word.Range wRange = wBookmark.Range;
wRange.Text = valueToSetInTemplate;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!