Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Word Office Automation - Filling Text Form Fields And Check Box Form Fields And Mail Merge

Does anyone have any good advice or experience on how to create an engine using C# (VB.NET is okay too) that is generic enough to handle most cases of MS Word text fields I need to fill with data I'm getting from a database? In short, I'm about to embark on this little Office automation excursion and I'm hoping a little bit of feedback here may help me to avoid some time consuming errors.

Cheers and thanks in advance for any advice;

Dave

like image 605
Daver Avatar asked Sep 03 '09 02:09

Daver


People also ask

How do you automate a form with custom fields in Word?

To set up those custom fields, go into the Info menu in Word, and on the right side of the screen, click on the dropdown arrow next to Properties > Advanced Properties. In this pop-up, you can add the recipient field by name. Select “text” as the type and the value. Click Add, and then OK.

How do I create a Word document that will autofill information?

To enable the option, go to File > Options > Advanced. In the Editing Options section, check the Show AutoComplete suggestions box. Click OK. Now, you should see your AutoText entry pop up when you start typing its name.

Can you automate mail merge?

Apply to each control in Power Automate is used to perform a series of actions for each row/entry you have in a list. That means it can be used to perform mail merge. In this example, I'll show you how you can send an email to a list of people, who have their details are stored in Excel.

What is mail merge in MS Word?

Mail merge lets you create a batch of documents that are personalized for each recipient. For example, a form letter might be personalized to address each recipient by name. A data source, like a list, spreadsheet, or database, is associated with the document.


1 Answers

I will sent two examples for solving your automation problem. The first one is using MailMerge and the second is using bookmarks.

The word file looks like this:

Using MailMerge (Insert - > Quick Parts -> Field -> Mail merge -> Merge field) First name: «firstName» Last name: «lastName»

=======

Using Bookmarks( Insert -> BookMark) First name: (<- the bookmark is here, it’s not visible) Last name:

And the code is following:

  1. Using bookmarks

        Open("D:/Doc1.doc");
        if (oDoc.Bookmarks.Exists("bkmFirstName"))
        {
            object oBookMark = "bkmFirstName";
            oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox1.Text;
        }
    
        if (oDoc.Bookmarks.Exists("bkmLastName"))
        {
            object oBookMark = "bkmLastName";
            oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox2.Text;
        }
    
        SaveAs("D:/Test/Doc2.doc"); Quit();
        MessageBox.Show("The file is successfully saved!");
    
  2. Using MailMerge

        Open("D:/Doc1.doc");
        foreach (Field myMergeField in oDoc.Fields)
        {
            //iTotalFields++;
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;
    
            // GET only MAILMERGE fields
            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
    
                fieldName = fieldName.Trim();
                if (fieldName == "firstName")
                {
                    myMergeField.Select();
                    oWordApplic.Selection.TypeText("This Text Replaces the Field in the Template");
                }
            }
        }
        SaveAs("D:/Test/Doc2.doc"); Quit();
        MessageBox.Show("The file is successfully saved!");
    

I've also used some helper methods.

    ApplicationClass oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
    private Microsoft.Office.Interop.Word.Document oDoc = new Document();

    public void Open(string strFileName)
    {
        object fileName = strFileName;
        object readOnly = false;
        object isVisible = true;
        object missing = System.Reflection.Missing.Value;

        oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

        oDoc.Activate();
    }

    public void SaveAs(string strFileName)
    {
        object missing = System.Reflection.Missing.Value;
        object fileName = strFileName;

        oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
    }

    public void Quit()
    {
        object missing = System.Reflection.Missing.Value;
        oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
    }

I hope that this implementation will give some ideas for solving your problem.

like image 120
ZokiManas Avatar answered Oct 02 '22 16:10

ZokiManas