Filling Word Template Fields with C #

Currently, if I create a Word Document template with margins and then fill them with 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 fields?

I notice that when I create the template, I can add a title and tag to the field, but I have not found a way to reference these properties. It would be nice to be able to name the fields and refer to them directly, instead of just counting and figuring out which field I'm in.

+3


source to share


2 answers


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

So, in VBA:

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

      

In your case, it could be (C #):

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

      



Or you could just write a loop that scans the list of fields and looks for the 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 are using new form field controls where you can set tag and automate with VSTO (C #):

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

      

Read more about Content Controls here .

+4


source


One good way to do this is at every place in the template you want to add text later, put a bookmark (Insert → Links → Bookmark). To use them from your code, you will 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;

      

+4


source







All Articles