How to do a Mail Merge in C# using Interop.Word?

梦想的初衷 提交于 2019-12-11 10:08:01

问题


I have a template in Word that would be used to print out invoices.

Now, I would like to know how to create a Word Document programmatically and copy the template content into the new document so that I still have a clean template, then replace placeholders that I have typed by using Mail.Merge. I found similar Mail.Merge questions but most require Spire components and I am not interested since it needs to be paid for. I am only a student. Others though, actually doesn't help that much.

The problems I am facing now are as follows:

  1. Create a Word document
  2. Copy template content into new document
  3. How to add placeholder names into MailMerge since I'm very confused about this.
  4. Do MailMerge

Here is the current code that I have concocted, this is actually the first time I have used Interops

Document document = new Document();
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
document = wordApp.Documents.Open(fileName);
string[] fieldNames = {"date_issued", "month_covered", "tuition", "lunchfee", "discount", "in_no", "student_no", "student_name", "amount_due", "amount_paid", "balance", "penalty", "status"};
string[] data = new string[25];
Range range;
document.MailMerge.Fields.Add(range, fieldNames[0]);
document.MailMerge.Execute();

I'm really confused on this part

document.MailMerge.Fields.Add(range, fieldNames[0]);

and I don't know what range is for


回答1:


If your template is an actual template and not a plain Word Document (with the extension .dotx or .dot, and not .docx/.doc), you don't need to copy anything. Just create a new document based on the template:

var doc = wordApp.Documents.Add("put template path here");

This will have the contents of your template. If you have used the Word UI to setup a mailmerge in the template (including the location of the data for the merge), that will also be carried over into the new document.

Then you can execute the mailmerge from C#:

doc.MailMerge.Execute();


来源:https://stackoverflow.com/questions/13180654/how-to-do-a-mail-merge-in-c-sharp-using-interop-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!