欢迎您访问我爱IT技术网,今天小编为你分享的编程技术是:【c# 实现Word联接Excel的MailMerge功能】,下面是详细的分享!
c# 实现Word联接Excel的MailMerge功能
目标:使用word的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。
关于Word的MailMerge功能:
word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。
为了实现这个功能,我的程序要能做的是
1:打开word文件对象
2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s
3:关闭保存
关于引用:
using Word=Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Diagnostics;
using System.IO;
关于变量:word的com对象需要传入的参数定义
Word.Application WordApp=new Microsoft.Office.Interop.Word.Application();
object missing=System.Reflection.Missing.Value;
object falseValue=false;
object trueValue=true;
关于处理
需要注意的是
1:打开word的方式
2:query的写法。类似于sql一般,比较好玩。
3:设置列,。设置之后,在word中可以看见这些列。
4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。
private void button1_Click(object sender, EventArgs e)
{
object fileName=CopyTemplateDoc();//copy doc in
Word.Document doc=WordApp.Documents.Open(ref fileName, ref missing, ref falseValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref trueValue, ref missing, ref missing, ref missing);
object linkTo=CopyExcelData();//copy excel data
object query="SELECT * FROM `Sheet1$`";//data from sheet1
object header="Name,Category,Address,Content";//filed list
try
{
doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
MessageBox.Show("success");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
doc.Save();//save word
CloseApp();//close word app
CopyExcelData();//copy data again,*******************
}
}
关于关闭word对象
public void CloseApp()
{
WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
WordApp.Quit(ref trueValue, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
GC.Collect();
//this.KillExcelProcess();
}
还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
以上所分享的是关于c# 实现Word联接Excel的MailMerge功能,下面是编辑为你推荐的有价值的用户互动:
相关问题:如何通过VS2010用C#实现对Excel等Office的操作
答:之前都是用VBA来开发Office解决方案的,后来微软开发出了VSTO这个工具包来创建自定义的Office应用程序,使得开发Office应用程序更加简单,并且用VSTO来开发office应用程序可以使用Visual studio开发环境中的众多功能和CLR提供的内存管理,垃圾回... >>详细
相关问题:如何使用C#实现打印ppt功能
答:powerpoint.Application apcprint = new powerpoint.ApplicationClass(); powerpoint.Presentations presprint = apcprint.Presentations; powerpoint.Presentation preprint = null; preprint = presprint.Open("c:\\a.pptx"(PPT所放的地址), o... >>详细
相关问题:winform(c#)双击打开文件或文件夹怎么实现,尤其...
答:System.Diagnostics.Process.Start("C:\\temp.txt"); 参数需要打开的文件名称,系统会自动取判断需要用什么类型的软件来打开它,你只需这么调用即可 >>详细
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
