I have Template and database in C drive with name Template.doc and SampleDB.mdb respectively.
Add Reference: Microsoft Word 11.0 Object Library from COM tab
using Word = Microsoft.Office.Interop.Word;
Word.Application wrdApp;
Word._Document wrdDoc;
Object oTemplate = "c:\\Template.doc";
Object oMissing = System.Reflection.Missing.Value;
Object oFalse = false;
Object oTrue = true;
Word.MailMerge wrdMailMerge;
// Create an instance of Word and make it visible.
wrdApp = new Word.Application();
wrdApp.Visible = true;
// Create MailMerge Data.
wrdDoc = wrdApp.Documents.Open(ref oTemplate, 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;
object oQuery = "SELECT Name,Address1,City from Table1";
string strDB = "c:\\SampleDB.mdb";
wrdDoc.MailMerge.OpenDataSource(strDB, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oQuery, ref oMissing, ref oFalse, ref oMissing);
wrdMailMerge.SuppressBlankLines = true;
// Perform mail merge.
wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
wrdMailMerge.Execute(ref oFalse);
// Close the Template document.
wrdDoc.Saved = true;
wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
// Release References.
wrdMailMerge = null;
wrdDoc = null;
wrdApp = null;
Wednesday, February 3, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment