如何使用Interop.Word在C#中进行邮件合并? [英] How to do a Mail Merge in C# using Interop.Word?

查看:387
本文介绍了如何使用Interop.Word在C#中进行邮件合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Word中有一个模板,用于打印发票.

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

现在,我想知道如何以编程方式创建Word文档并将模板内容复制到新文档中,以便我仍然拥有一个干净的模板,然后替换使用Mail.Merge键入的占位符.我发现了类似的Mail.Merge问题,但大多数问题都需要Spire组件,并且我不感兴趣,因为需要付费.我只是一个学生.但是,其他人实际上并没有太大帮助.

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. 创建Word文档
  2. 将模板内容复制到新文档中
  3. 由于我对此感到非常困惑,因此如何在MailMerge中添加占位符名称.
  4. 执行MailMerge
  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

这是我编写的当前代码,这实际上是我第一次使用Interops

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

我对这部分真的很困惑

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

我不知道range是什么

推荐答案

如果您的模板是实际模板而不是纯Word文档(扩展名为.dotx或.dot,而不是.docx/.doc),则您不需要复制任何内容.只需根据模板创建一个新文档:

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

这将包含您模板的内容.如果您已使用Word UI在模板中设置邮件合并(包括合并数据的位置),则该邮件合并还将被带入新文档中.

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.

然后您可以从C#执行邮件合并:

Then you can execute the mailmerge from C#:

doc.MailMerge.Execute();

这篇关于如何使用Interop.Word在C#中进行邮件合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆