Goal: Use the MailMerge feature of Word, the data source is data in Excel. This information is very little on the internet and can only be tested slowly.
About Word's MailMerge features:
Word provides a template for the message, you can choose a variety of data sources, such as databases, Excel, and then mass (or print, save files) mail.
In order to achieve this function, what my program has to do is
1: Open the Word file object
2: Set the MailMerge data source: Specify Excel, specify the query statement, specify the joined columns s
3: Close Save
About references:
Using Word = Microsoft.Office.Interop.Word;
Using System.Reflection;
Using System.Diagnostics;
Using System.IO;
About variables: Word's COM object requires an incoming parameter definition
Word.Application WordApp = new Microsoft.Office.Interop.Word.Application ();
Object missing = System.Reflection.Missing.Value;
Object falsevalue = false;
Object truevalue = true;
About handling
It is to be noted that
1: How to open Word
2:query's writing. Similar to SQL General, more fun.
3: Set the column,. After setting, you can see these columns in Word.
4: After word is turned off, you will have to copy Excel once again. The Excel file size soared after the direct build, and the file was not open, so cover it up again. The reason is unknown.
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 missin g, 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 m Issing, 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,*******************
}
}
About closing Word objects
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 ();
}
There are also two tool functions that are no longer repeating, used to copy files and return the file name private string Copyexceldata (); and private string Copytemplatedoc ().