MailMerge:从 Excel 到 Word C#

MailMerge: From Excel to Word C#

我目前遇到有关 MS Word 的 MailMerge 功能的问题。

我不得不将旧的 VBA 应用程序重写为 C#。我几乎完成了。新应用程序工作正常。 除了一个我无法摆脱的弹出窗口。

因此,过去 2 天我一直在网上四处寻找,因为我们的客户不希望它弹出,因为它在旧应用程序中不存在。 但是我找不到合适的解决方案。除了少数人提到连接字符串可能不正确。但我没有找到任何资源告诉我它在 C# 代码中的外观

这是它在旧应用程序中的样子:

Word.ActiveDocument.MailMerge.OpenDataSource Name:=strSourceDoc, ConfirmConversions:=False, _
        ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", WritePasswordDocument:="", WritePasswordTemplate:="", _
        Revert:=False, Format:=wdOpenFormatAuto, Connection:= _
        "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" & strSourceDoc & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";" _
        , SQLStatement:="SELECT * FROM `Tabelle1$`", SQLStatement1:="", SubType:= _
        wdMergeSubTypeAccess

我显然已经尝试获取该连接密钥并在我的代码中使用它。但这并不能阻止弹出窗口。我还尝试使用子类型。但它要么不改变任何东西,要么抛出格式异常。

这是在 C# 中工作的内容:

mailApp.ActiveDocument.MailMerge.OpenDataSource(processedPath + file, true, false, true, 
    true, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
   "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" + 
    processedPath + file + ";Mode=Read;", 
   "SELECT * FROM 'Tabelle1$'", 
   ref oMissing, ref oMissing, ref oMissing,
   Word.WdMergeSubType.wdMergeSubTypeAccess);

如何更改连接字符串以防止弹出窗口显示?

所以我找到了一个解决方案,它以某种方式起作用。

实际问题(至少从我的测试来看)是文件扩展名而不是连接字符串。我使用 .xlsx 文件作为我的源文件。但是,一旦我测试了一些 xls 文件,弹出窗口就消失了。

我刚刚拍了一张"google session"来找出xls和xlsx的区别

所以我可以更改我的代码以仅处理 xls 文件。问题解决了。但对我来说仍然是一个令人不快的解决方案。

如果您想稍微测试一下,也许可以让它与 xlsx 一起使用。这是一些用于测试的代码(只需将其绑定在 winforms 中的按钮单击或其他东西上)

 class PerformMailMerge
    {
        Word.Application mailApp;
        Object oMissing = System.Reflection.Missing.Value;
        Object oFalse = false;
        string _path = @"Your Path to Excel File";
        string savePath = @"Your Path to Word Document";

        public void mailMerge2()
        {
            mailApp = new Word.Application();
            mailApp.Visible = false;

            mailApp.Documents.Add();

            mailApp.ActiveDocument.MailMerge.MainDocumentType = Word.WdMailMergeMainDocType.wdMailingLabels;

            //OpenDataSource: 
            mailApp.ActiveDocument.MailMerge.OpenDataSource(_path,
                Word.WdOpenFormat.wdOpenFormatAllWordTemplates, true, true, true,
                ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, "TABLE Tabelle1$", "SELECT * FROM `Tabelle1$",
                ref oMissing, ref oMissing,
                Word.WdMergeSubType.wdMergeSubTypeWord2000);

            mailApp.ActiveDocument.SaveAs2(savePath);
            mailApp.ActiveDocument.Close();
            mailApp.Quit();
        }    
    }

编辑: 因此,以防万一有人再次偶然发现这一点。我找到了解决问题的办法。解决方案是不指定 WdMergeSubType。这允许从 xlsx 文件中读取并且仍然不显示弹出窗口!