I have created a simple C# Winforms Application. This application allows the user to query a 400 system for data, select desired records, and then write selected records to a .txt file. The .txt file is then used as the data source for a Microsoft Word Mail Merge operation. Below is Mail Merge outline:
This is my code for writing the data to the .txt file:
private void btnMerge_Click(object sender, EventArgs e)
{
try
{
string docLoc = "";
string docSource = "";
StringBuilder sb;
// Change this to the DataSource FilePath
StreamWriter sw = new StreamWriter("C:\\Users\\NAME\\Desktop\\Test2.txt");
string fileHeaderTxt = "memno!name!address1!address2!sys!fuldate!sal!address3";
sb = new StringBuilder();
sb.Append(fileHeaderTxt);
sw.WriteLine(sb.ToString());
sb.Clear();
if (lvData.Items.Count > 0)
{
foreach (ListViewItem lvI in lvData.Items)
{
var indices = new int[] { 0, 1, 2, 3, 12, 13, 16, 17 };
foreach (int i in indices)
{
sb.Append(string.Format("{0}!", lvI.SubItems[i].Text));
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
sw.WriteLine();
}
switch (cmbLetterType.SelectedIndex)
{
case 0:
docLoc = "\\\\file\\...\\B-AIAddChgDual10-06-PREV.doc";
docSource = "\\\\file\\...\\B-AIAddChgDual10-06-PREV.txt";
break;
case 1:
docLoc = "\\\\file\\...\\B-AIAddChgDual10-06-NEW.doc";
docSource = "\\\\file\\...\\B-AIAddChgDual10-06-NEW.txt";
break;
case 2:
docLoc = "\\\\file\\...\\BothNCAckDist.doc";
docSource = "\\\\file\\...\\BothNCAckDist.txt";
break;
}
//sb.Clear();
sw.Close();
MessageBox.Show("Complete");
if (rbPrint.Checked)
{
Print(docLoc, docSource);
}
if (rbCommit.Checked)
{
Commit_NetFYI();
}
}
catch (Exception ex)
{
MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
}
finally
{
//
}
}
This is my code for executing the MailMerge operation:
public void Print(string docLoc, string docSource)
{
try
{
Word.Application oWord = new Word.Application();
Word.Document oWrdDoc = new Word.Document();
oWord.Visible = true;
Object oTemplatePath = "C:\\Users\\NAME\\Desktop\\B-AIAddChgDual10-06-NEW.doc";
oWrdDoc = oWord.Documents.Open(oTemplatePath);
Object oMissing = System.Reflection.Missing.Value;
oWrdDoc.MailMerge.OpenDataSource("C:\\Users\\NAME\\Desktop\\Test2.txt", oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
oWrdDoc.MailMerge.Execute();
}
catch (Exception ex)
{
MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
}
finally
{
//
}
}
When the operation is completed, I get all the documents like I would expect, but I also get a word document with the following:
Can someone tell me why I am getting the Mail Merge Errors document when I am providing 8 specific data source fields to 8 specific Mail Merge fields?