【发布时间】:2013-11-18 17:16:14
【问题描述】:
我创建了一个简单的 C# Winforms 应用程序。该应用程序允许用户查询 400 系统的数据,选择所需的记录,然后将选定的记录写入 .txt 文件。然后将 .txt 文件用作 Microsoft Word 邮件合并操作的数据源。以下是邮件合并大纲:
这是我将数据写入 .txt 文件的代码:
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
{
//
}
}
这是我执行 MailMerge 操作的代码:
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
{
//
}
}
操作完成后,我得到了我期望的所有文档,但我也得到了一个包含以下内容的 word 文档:
当我向 8 个特定的邮件合并字段提供 8 个特定的数据源字段时,有人能告诉我为什么会收到邮件合并错误文档吗?
【问题讨论】:
标签: c# winforms ms-word office-interop mailmerge