Question

I would like to automate printing invoices from a Word Template. I think I have the logic down but I just don't know the right way of coding it. Here is my current code

Selection wrdSelection;
MailMerge wrdMailMerge;
MailMergeFields wrdMergeFields;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Document wrdDoc = new Document();
wordApp.Visible = false;
wrdSelection = wordApp.Selection;

object oMissing = System.Reflection.Missing.Value;

// PUT MY EXISTING TEMPLATE FILE INTO WORD DOCUMENT
wrdDoc = wordApp.Documents.Add(Properties.Resources.invoiceTemp,oMissing,oMissing, oMissing);
// RETREIVE MAIL MERGE PROPERTIES FROM THE DOCUMENT IN HOPES OF UTILIZING IT

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

If it would help, here are the Merge Fields that I have on my template:

date_issued, month_covered, invoiceNo, tuition, lunchFee, discount, studentNo, studentName, amountDue, amountPaid, balance, penalty, status

Now, how do I add data that I retrieve using my Application into the document which gets all the properties from the template?

Was it helpful?

Solution

Here are some notes on running with a template and data file.

Word.Application _wordApp = new Word.Application();
Word.Document oDoc = _wordApp.Documents.Add(@"z:\docs\mergetemplate.dotx");
_wordApp.Visible = true;
oDoc.MailMerge.MainDocumentType = Word.WdMailMergeMainDocType.wdFormLetters;
oDoc.MailMerge.OpenDataSource(@"Z:\Docs\new.csv", false, false, true);
oDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
oDoc.MailMerge.Execute(false);

The newly created merge file is now the active document, so you can save it:

Word.Document oLetters = _wordApp.ActiveDocument;
oLetters.SaveAs2(@"z:\docs\letters.docx", 
     Word.WdSaveFormat.wdFormatDocumentDefault);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top