【问题标题】:How to do a Mail Merge in C# using Interop.Word?如何使用 Interop.Word 在 C# 中进行邮件合并?
【发布时间】:2012-10-22 06:02:23
【问题描述】:

我在 Word 中有一个用于打印发票的模板。

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

我现在面临的问题如下:

  1. 创建 Word 文档
  2. 将模板内容复制到新文档中
  3. 如何将占位符名称添加到 MailMerge,因为我对此感到非常困惑。
  4. MailMerge

这是我目前编写的代码,这实际上是我第一次使用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 是干什么用的

【问题讨论】:

标签: c# printing interop ms-word placeholder


【解决方案1】:

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

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

这将包含您模板的内容。如果您使用 Word UI 在模板中设置了邮件合并(包括合并数据的位置),该邮件也将被转移到新文档中。

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

doc.MailMerge.Execute();

【讨论】:

  • 我其实不知道你说的是什么数据源。如何通过 c# 以编程方式添加数据?以及如何在 Word 中创建实际模板?
  • 我刚刚在答案中澄清了这一点。
  • 如果你想使用一些你已经拼凑到内存中的DataTable中的数据作为合并的源?
  • 我认为 Word 本身不支持使用 DataTable 作为合并源。您必须首先将其输出到 Word 可以使用的某个数据源:CSV、Excel、Access 等。或者,您可以以编程方式遍历文档,并将每个合并字段替换为 DataTable 中的相应值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 2010-09-07
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多