MS Word Automation

This time I will try to demonstrate how to manipulate Microsoft Word and use it to print reports because it is necessary in some projects to use such as features instead of report generators like Crystal Reports.

Let's start

1. Crete a Word document and write your text and select the text that will be replaced with a bookmark, then insert a bookmark as shown in this figure:

Ms-Word-Automation-1.jpg


NB: the bookmark will hold the data we pass from our application to the Word application.

After clicking "Insert", a bookmark a window will be shown to ask you to give a name to that bookmark. Be careful, the name will be used in our application as a variable so give it an appropriate name.

Ms-Word-Automation-2.jpg

Save your document in a known path, for example "C:\test.docx".
 
2. Add the COM reference shown in this figure to automate Microsoft Word.

3. Create this window in your application:

Ms-Word-Automation-3.jpg
4. Implement the following code in the pass button click:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using word=Microsoft.Office.Interop.Word; //  COM reference to automate word

 

namespace WindowsFormsApplication5

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            object missing = System.Reflection.Missing.Value;

            object file = Application.StartupPath+@"\1.docx"; //  the DOCX file path we created

            word.Application w = new word.Application();   

            word.Document f = new word.Document();

            f=w.Documents.Add(file,ref missing,ref missing,ref missing);

            f.Bookmarks["bk1"].Range.Text = textBox1.Text; //bk1 name of the bookmark we created

            w.Visible = true;

        }

    }

}

When you click the button PASS, what is written in the TextBox will be transferred to the bookmark in the Word document and the Word document will be shown to you.

Hope you find this tutorial helpful, please leave a comment and see you soon.

Up Next
    Ebook Download
    View all
    Learn
    View all