Word Automation in C#

11. November 2009 19:44

C#  13 Comments

Here in this tutorial I have used a word document template and mail merge option of the Word to automate the word document creation.
I have use mail merge option to set the fields and make the document fill through my application. We can also set the location of the text that we want to display in the word document programmatically.
So to get started we have to first make a template which is a word document template file (.dot file).

Open a new word document. Design the template as you like and once you are done then save the document in a word 97-2009 template.

Once the document is designed, it’s now time to set the merge fields. To set the mail merge fields in word 2007navigate to Insert>Quick Parts>Fields

Select “Merge Field” from the “Field names:” and give a “Field Name:” a name which we will need in our code.

Likewise, we need to set all the fields in the document and in the end the document looks like this:

Create a new windows application in Visual Studio.

Design application so that you have all the text fields. I have created small and very simple interface to demonstrate this automation.

Coming to the code part……

As we are performing office automation we first need to add requisite libraries.
Library name can be different as it depends on the office version installed on your machine. To add reference in your application, right-click “References” in solution explorer.

You will be prompted with Add Reference box.

Here under .NET tab choose Microsoft.Office.Interop.Word. You need to check the version as office 2003 and office 2007 will get different version installed on the system. Select the appropriate version and click OK.
When you add the reference, you will see the following reference added under reference which you can see under solution explorer.

To get the word document reference in the code we need to use the below references (namespaces).

using Microsoft.Office;
using Word = Microsoft.Office.Interop.Word;

Initialize the word application with word document

Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();

To make sure that the application preview the word document, set the Visible property to true of word application.

oWord.Visible = true;

Set the template path This is the same word template file which you have created.

Object oTemplatePath = System.Windows.Forms.Application.StartupPath+"\\Report.dot";

Then pass the template object path to the word document object.

oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

Now count all merge fields in the document so we can have the field name through which we can access their location in the document. We are not, in actual accessing the location but want their reference so we can set their text and auto fill the document. I have used foreach loop to traverse all the merge fields.

foreach (Word.Field myMergeField in oWordDoc.Fields)
	Word.Range rngFieldCode = myMergeField.Code; 
	String fieldText = rngFieldCode.Text;
	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 == "Name")

One thing that you should notice that the merge field starts with MERGEFIELD <Mergefield name> for e.g.: in our case all the fields are like this MERGEFIELD\\NAME. MERGEFIELD\\ADDRESS, and likewise for every mergefield.
And in the end a simple if condition which check the name of the field and update the field text.

Execute you application and fill in all the text boxes in the application and hit Generate button, after which you will see the document completed.


Download: WordDemo.zip (51.65 kb)

Currently rated 4.6 by 10 people

Comments (13)

sherifffruitfly sherifffruitfly
12/25/2009 12:12:39 AM #

All dev time spent coding up Word for server-style use is better spent convincing idiot PM's not to. It will end in tears.

Maikalal Maikalal
9/10/2011 10:38:16 AM #

Hey Prashant..............Gr8 job....you are gr8....

shohel shohel
11/26/2011 11:57:54 PM #

Thank you. I will be really appretiate if you can convert it to asp.net and c#. I don't know much about it but i need it for one of my project. Thnx in advance

omer oruc omer oruc
1/31/2012 8:13:49 PM #

hi! thx for code how can i make automatically save the word file ? i want to save and print directly can you help to me ?

Prashant Prashant
1/31/2012 10:13:57 PM #

I haven't tried saving the file automatically. I doubt if it is possible with the old office interop to save the file when using a word template file.

Chase Chase
3/22/2012 5:28:21 AM #

It works in debug mode but once i build and publish, the form come up and when i hit generate i get the error message ystem.Runtime.InteropServices.COMException (0x800A141F): Word was unable to read this document. It may be corrupt. Try one or more of the following: * Open and Repair the file. * Open the file with the Text Recovery converter. at Microsoft.Office.Interop.Word.Documents.Add(Object& Template, Object& NewTemplate, Object& DocumentType, Object& Visible). I can only get it to work in debug mode. What am I missing?

Prashant Prashant
3/24/2012 11:55:38 AM #

Which version of MS Office you are using? I build this application on MS Office 2007. Are you using a word template file (.dot)? I never encountered this problem but I believe this is due to the miss-match of the office library used in the application.

Surya Surya
8/30/2012 3:19:39 PM #

Hi, I used your code it was really nice, and working well on my local system. But went i deployed the same to Server, it gave me below error... Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). Do you have any comment on the same ?

Prashant Prashant
8/31/2012 9:12:00 PM #

I faced this error when I have referenced a different version of libraries in my application than that of the version of office installed on my machine. Try using the same version of the office.

Rutuja Rutuja
9/12/2014 3:31:20 PM #

Hi Prashant, Would you know how can I replace image in a word dotx template?

Prasant Prasant
9/20/2014 7:06:37 AM #

@Rutuja: Not sure...It's long time when I did that. But it is possible.

Sangeetha Sangeetha
4/26/2016 12:24:01 PM #

Hi Prashant, I have the same functionality requirement and it is working fine(C# code) but I have an additional requirement which is my word template should have building blocks(controls) and have to convert this template into word document with controls being replaced by values. If you could provide any solution it will be really helpful.

Prashant Prashant
5/14/2016 5:08:34 PM #

Hi Sangeetha, I didn't get the meaning when you said controls. Are you talking about text boxes, buttons etc. Also are you using word template files (.dot)?

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs