目標:使用Word的MailMerge功能,數(shù)據(jù)源是Excel中的數(shù)據(jù)。這些資料在網(wǎng)上很少,只能自己慢慢測試了。
關(guān)于Word的MailMerge功能:
word提供郵件的模板,可以選擇各種數(shù)據(jù)源,比如數(shù)據(jù)庫,excel等,然后群發(fā)(或打印、另存文件)郵件。
為了實現(xiàn)這個功能,我的程序要能做的是
1:打開word文件對象
2:設(shè)置MailMerge數(shù)據(jù)源:指定Excel,指定查詢語句,指定聯(lián)接的列s
3:關(guān)閉保存
關(guān)于引用:
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Diagnostics;
using System.IO;
關(guān)于變量:word的com對象需要傳入的參數(shù)定義
Word.application WordApp = new Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
object falseValue = false;
object trueValue = true;
關(guān)于處理
需要注意的是
1:打開word的方式
2:query的寫法。類似于sql一般,比較好玩。
3:設(shè)置列,。設(shè)置之后,在word中可以看見這些列。
4:關(guān)閉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,*******************
}
}
關(guān)于關(guān)閉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();
}
還有兩個工具函數(shù)不再贅述,用來copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
測試,搞定
新聞熱點
疑難解答