Word Automation Code

Word Automation Code

February 20th, 2006 // 3:30 pm @


Here is the sample code to get Word Automation working. Assuming that you have already added the reference to the Word dll‘s to your project.

Create a datasource file (*.odc) in Word by choosing Mail Merge option, and when it asks to select a data source, choose to create a new one and save the .odc file to your web folder. Store the password in the file and do not select any specific table in it.

Word.Application wrdApp;
Word._Document wrdDoc;

object oMissing = System.Reflection.Missing.Value;
object oFalse = false;
object oTrue = true;

Word.MailMerge wrdMailMerge;


// Create an instance of Word
wrdApp = new Word.Application();
wrdApp.Visible =
false;

// Open the template document.
string TemplateFile = TemplateFilePath + selectedTemplate;
object oFile = Server.MapPath(TemplateFile); wrdDoc = wrdApp.Documents.Open(ref oFile, ref oMissing,ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

wrdDoc.Select();
wrdMailMerge = wrdDoc.MailMerge;

// Create a MailMerge Data file.
object oSql = “Select * from “ + viewName + ” where Account <> ‘NULL’”;
string ODCFile = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["ODCFile"]); wrdDoc.MailMerge.OpenDataSource(ODCFile,ref oMissing,ref oMissing,ref oFalse,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oSql,ref oMissing,ref oFalse,ref oMissing);

wrdMailMerge.SuppressBlankLines = true;


// Perform mail merge.
wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToPrinter;
wrdMailMerge.Execute(
ref oFalse);

if(wrdDoc != null)
{

wrdDoc.Saved = true;
wrdDoc.Close(
ref oFalse,ref oMissing,ref oMissing);

}

if(wrdApp != null)
{

wrdApp.Quit(ref oFalse,ref oMissing,ref oMissing);

}

// Release References.
wrdMailMerge = null;
wrdDoc =
null;
wrdApp =
null;

Posted at DotNetJunkies on Wednesday, October 13, 2004 4:35 PM


Category : Miscellaneous

Leave a Reply

Latest Posts

Testimonials

"Amar clearly has a thorough knowledge of Sharepoint, this knowledge, coupled with his professionalism and dedication made him a tremendous asset to the project. He was the key contributor to the later stages of the project delivery effort (the really difficult bit, long hours and hard work that puts huge demands on people), and I can state categorically that without his focussed dedication and hard work we would not have been able to meet the timescales imposed upon the project."

Tim Ellis , Sharepoint Project Manager , Royal Bank of Scotland

Subscribe Now