A day with .Net

My day to day experince in .net

Create a Word Document From a Template using c# (Mail Merge)

Posted by vivekcek on August 25, 2012

I want to create a word document from a word template.The advantage of using template is, we can define a structure for the document and decorate the it with dynamic text.

Software’s Used
——————————–

1. Word 2007.

2. Visual Studio 2010

Library used
—————————–

1. Microsoft Word 12.0 Object Library

Steps
———————-

1. Create a Word Template.

2. Create a console application using VS 2010.

3. Add reference to Microsoft Word 12.0 Object Library.

4. Enjoy 🙂

1. Create a Word Template.
——————————————-

Word templates are created using MergeField’s in word.

a. Open a new Word 2007

b. Type “Name:”, Where ‘Name:’ is just a label.

c. Now we need to insert a MergeField right to our label ‘Name:’

d. Place cursor on the right of our label.

e. Select insert tab in word.

f. Select Quick Parts. Then Field.

g. Select field category as MergeField. Give the MergeField name as ‘Name’.

h. Save the document as WordTemplate.

Now our Template contains.

Name: «Name»

The field inside <> is our merge Field. We will replace that field through code to create a new word document.

* Note the extension of out template will be .dotx(MyTemplate.dotx)

2. Create a console application using VS 2010.
—————————————————————
a. Create a console application.

b. Add refrence to Microsoft Word 12.0 Object Library.

c. Add NameSpace “using Microsoft.Office.Interop.Word;”.

d. The Final document will be save in MyDocuments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace WordAuto
{
    class Program
    {
        static void Main(string[] args)
        {
            //OBJECT OF MISSING "NULL VALUE"

            Object oMissing = System.Reflection.Missing.Value;

            Object oTemplatePath = "D:\\MyTemplate.dotx";

            
            Application wordApp = new Application();
            Document wordDoc = new Document();

            wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

            foreach (Field myMergeField in wordDoc.Fields)
            {

                
                Range rngFieldCode = myMergeField.Code;

                String fieldText = rngFieldCode.Text;



                // ONLY GETTING THE MAILMERGE FIELDS

                if (fieldText.StartsWith(" MERGEFIELD"))
                {

                    // THE TEXT COMES IN THE FORMAT OF

                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT

                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

                    Int32 endMerge = fieldText.IndexOf("\\");

                    Int32 fieldNameLength = fieldText.Length - endMerge;

                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//

                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

                    if (fieldName == "Name")
                    {

                        myMergeField.Select();

                        wordApp.Selection.TypeText("Vivek");

                    }

                }

            }
            wordDoc.SaveAs("myfile.doc");
            wordApp.Documents.Open("myFile.doc");
            wordApp.Application.Quit();
        }
    }
}

DOWNLOAD SOURCE

http://sdrv.ms/NQmKeD

34 Responses to “Create a Word Document From a Template using c# (Mail Merge)”

  1. Umair said

    thanks

  2. titasix said

    Simple but amazing. Thx

  3. Amit said

    It worked but when i put IF conditions on Merge field its not working as expected, can you suggest any solution for this?

  4. WIBI KURNIAWAN said

    THIS IS WHAT I NEED !!!, THANK YOU

  5. dinesh kumar said

    Thanks……………………..

  6. shubhangi said

    hi this is amazing stuff what u have posted but i wnat number of copies of the letter for different number of agent…how do i perform this with you code plz sugggest

  7. Sam Chang said

    Many thanks, this is exactly what I need!

  8. A user said

    Hi, thanks you. May i know how to set path for below two? i try out this two line code save the file in different path…
    wordDoc.SaveAs(“myfile.doc”);
    wordApp.Documents.Open(“myFile.doc”);

    • robert said

      string fileName = @”C:\Users\yourUSR\Desktop\myfile.doc”;
      wordDoc.SaveAs(fileName);
      Process.Start(“WINWORD.EXE”, fileName);

  9. Peter J. said

    If you use COM on server side (e.g. ASP.NET) you would probably have problems like this: http://support.microsoft.com/kb/257757.

    You can try out this library http://flexdoc.codeplex.com/ which is free or some good but affordable third party like http://www.docentric.com.

  10. Arnold Wiersma said

    Thanks, this works great for the body of the document. Does anyone here know how to access the fields in the header and footer for office 2010?

  11. Murugavel S said

    hi,
    Excellent.

    But how to be configured the Field names are get from DB.
    please help me

    Murugavel S

  12. And to fill in various fields?
    Help me please

  13. Aravind said

    Its very good for one or two fields,but I need to get a bunch of data merged by connecting to the sql server please help

  14. hossein said

    similiar job with image possible?

  15. Momo said

    Thank you very much!!!!! Very easy to learn!!

  16. Dhananjay said

    Thank u but this code not working on server when i am hosting my web application on server, So please suggest me ??? what can i do???

  17. Rajesh said

    great great great … simply amazing !!! Just one query can i use this in table view ?

  18. pradeep said

    Hi all, If the fieldname consits of “\”value name \”” ..? then. What is the solution please help me.

  19. mmc said

    I want to do the same for bulk . i.e. letters should open in bulk for different values for the same mergefield in one document and data in there should come from the SQL server database.

  20. PS said

    Thank you. It helps me over dificully

  21. Sangeetha said

    @dhananjay,
    if it is not working after getting deployed to server that’s mainly because some .dll might be missing. check for msvcp…..

  22. Sangeetha said

    @dhananjay,
    if its not working after getting deployed in server that’s because some dll might be missing check for msvcp…………

  23. Hugh said

    How can you go about merging mailing labels which required to loop through a set of records (from Linq var List)? which is more a like real world problem?
    Thanks

  24. raja said

    showing error in

    wordDoc.SaveAs(“myfile.doc”);
    wordApp.Documents.Open(“myFile.doc”);
    wordApp.Application.Quit();

    in these lines

  25. vibhusha said

    is it works on web application ?

  26. vibhusha said

    i’ts working fine , thank you so much vivekcek.

    now my question is,
    how to set multiple values on word, the value is getting from database.

  27. Local save said

    I am trying to use this code in asp.net core (3.1) web API.
    But it is showing version issue for interop 15.00

  28. Chandru said

    Hi Vivek – it worked great for me! Thanks.

    Can you pls advise how the same can be extended to merge tabular data? I have a doc which is a mix of may headers and details… For eg. a Bank and its branches… I have the list of branches for any given bank in a table which has cols like branch name, address, manager, contact no etc… My document template has bank name on the top and the branch details in a tabular format. I dont know how many branches may be there for the bank so, my template defines just one row with 4 cols – branch name, address, manager, contact no. I intend to use TableStart and TableEnd to demark start and end of row…

    In this scenario, pls advise how your program can be extended to do the document merge?

  29. Chandru said

    This worked very well for me. Thanks. Do you have a similar sample code for filling tabular data in the template? In my case, number of rows are variable but cols are fixed. For e.g. Bank and branches – for every bank, there can be n no of branches but the branch details are fixed – branch name, address, manager, contact no.

Leave a comment