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
You must be logged in to post a comment.