gpt4 book ai didi

c# - MailMerge:从 Excel 到 Word C#

转载 作者:行者123 更新时间:2023-12-04 22:34:06 26 4
gpt4 key购买 nike

我目前正面临有关 MS Word 的 MailMerge 功能的问题。

我不得不将旧的 VBA 应用程序重写为 C#。我几乎已经完成了。新应用程序工作正常。
除了一个我无法摆脱的 PopUp。
enter image description here

因此,过去 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

我显然已经尝试使用该连接 key 并在我的代码中使用它。但这并不能阻止弹出。我也尝试过使用子类型。但它要么不会改变任何东西,要么会引发格式异常。

这是在 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 文件进行测试,弹出窗口就消失了。

我刚刚参加了一个“谷歌 session ”来找出 xls 和 xlsx 之间的区别。

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

如果您想进行一些测试以使其与 xlsx 一起使用。这是一些要测试的代码(只需将其绑定(bind)在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 文件中读取并且仍然不显示弹出窗口!

关于c# - MailMerge:从 Excel 到 Word C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com