3

我想从 Word 模板自动打印发票。我想我的逻辑是错误的,但我只是不知道正确的编码方式。这是我当前的代码

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;

如果有帮助,这里是我的模板上的合并字段:

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

现在,如何将使用我的应用程序检索的数据添加到从模板中获取所有属性的文档中?

4

1 回答 1

3

以下是使用模板和数据文件运行的一些注意事项。

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);

新创建的合并文件现在是活动文档,因此您可以保存它:

Word.Document oLetters = _wordApp.ActiveDocument;
oLetters.SaveAs2(@"z:\docs\letters.docx", 
     Word.WdSaveFormat.wdFormatDocumentDefault);
于 2012-11-02T13:15:00.947 回答