你如何邮件合并c#中的word文档

我想要实现的目标

在我的c#应用程序中,我想从我的应用程序中的数据生成报告(word文档),我认为最好的方法是使用我的应用程序中的数据源执行类似邮件合并的操作。

我试过的

  1. 我尝试将此邮件合并改为单词但是这使用了您需要支付的GemBox
  2. 我尝试过使用Microsoft.Office.Interop.Word,但是当我不知道如何引用保存的模板文档时,我做不到:

    Dictionary MailMerge = new Dictionary() { { "ID", "123" }, { "Name", "Test" }, { "Address1", "Test" }, { "Address2", "Test" }, { "Address3", "Test" }, { "Address4", "Test" }, { "PostCode", "Test" }, { "Year End", "Test" }, { "SicCode", "123" }, }; Document doc = new Document(); doc.MailMerge.Execute(MailMerge); 

摘要

我正在寻找一些关于进一步研究的指导,因为我认为必须有一种“标准”方式来做到这一点。

使用Microsoft.Office.Interop.Word非常简单。 是一个简单的分步教程,介绍如何执行此操作。

用字符串替换合并域的代码如下:

 public static void TextToWord(string pWordDoc, string pMergeField, string pValue) { Object oMissing = System.Reflection.Missing.Value; Object oTrue = true; Object oFalse = false; Word.Application oWord = new Word.Application(); Word.Document oWordDoc = new Word.Document(); oWord.Visible = true; Object oTemplatePath = pWordDoc; oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); foreach (Word.Field myMergeField in oWordDoc.Fields) { Word.Range rngFieldCode = myMergeField.Code; String fieldText = rngFieldCode.Text; if (fieldText.StartsWith(" MERGEFIELD")) { Int32 endMerge = fieldText.IndexOf("\\"); Int32 fieldNameLength = fieldText.Length - endMerge; String fieldName = fieldText.Substring(11, endMerge - 11); fieldName = fieldName.Trim(); if (fieldName == pMergeField) { myMergeField.Select(); oWord.Selection.TypeText(pValue); } } } } 

最初发布在这里和这里

如果您希望使用字典一次替换多个字段,请使用以下代码:

 public static void TextToWord(string pWordDoc, Dictionary pDictionaryMerge) { Object oMissing = System.Reflection.Missing.Value; Object oTrue = true; Object oFalse = false; Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document(); oWord.Visible = true; Object oTemplatePath = pWordDoc; oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); foreach (Microsoft.Office.Interop.Word.Field myMergeField in oWordDoc.Fields) { Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code; String fieldText = rngFieldCode.Text; if (fieldText.StartsWith(" MERGEFIELD")) { Int32 endMerge = fieldText.IndexOf("\\"); Int32 fieldNameLength = fieldText.Length - endMerge; String fieldName = fieldText.Substring(11, endMerge - 11); fieldName = fieldName.Trim(); foreach (var item in pDictionaryMerge) { if (fieldName == item.Key) { myMergeField.Select(); oWord.Selection.TypeText(item.Value); } } } } } 

我也使用相同的东西,但我有更多的复杂性。 我还要检查if条件。 在单词模板文件{IF«Installment»= Monthly“中,表格将显示”“无需显示”}

当我在答案中使用上面的代码时。 如果c#中的条件我写了

 Range rngFieldCode = myMergeField.Code; String fieldText = rngFieldCode.Text.Trim(); if (fieldText.ToUpper().StartsWith("IF")) { myMergeField.UpdateSource();} 

所以输出就像

{IF Monthly = Monthly“然后表格将显示”“无需显示”}

但是所需的输出只是“那么表格会出现”。