C# – Filling Word template fields with C#

cms-wordoffice-interopword-fieldword-template

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.

Best Answer

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;
Related Topic