简体   繁体   English

在 C# 中保存来自 Word mailmerge 的新文档结果

[英]save the new document result from Word mailmerge in C#

I am performing a mail merge to new document using Word for Office 365我正在使用 Word for Office 365 对新文档执行邮件合并

I am trying to save the new document to specified location.我正在尝试将新文档保存到指定位置。 However I don't know how to get a reference to this new document that is created after MailMerge.Execute.但是我不知道如何获得对在 MailMerge.Execute 之后创建的这个新文档的引用。

I'm currently using ActiveDocument, but there is another document 'in the way' (I'm guessing it is the document with errors) that I have to close in addition to the original document that I close until ActiveDocument is something I want to save.我目前正在使用 ActiveDocument,但是除了我关闭的原始文档之外,我还必须关闭另一个文档“挡路”(我猜它是有错误的文档),直到 ActiveDocument 成为我想要的东西节省。

Is there a more robust way of getting a reference to the document created by MailMerge.Execute?是否有更可靠的方法来获取对 MailMerge.Execute 创建的文档的引用?

  static void Main(string[] args)
    {
        string inDoc = @"C:\bob\doc.docx";
        string data = @"C:\bob\data.csv";
        string outDoc = @"C:\bob\out.docx";

        Application wordApp = new Application();
        Document wordDoc = wordApp.Documents.Open(inDoc);

        wordDoc.MailMerge.OpenDataSource(data);

        wordDoc.MailMerge.Destination = WdMailMergeDestination.wdSendToNewDocument;
        wordDoc.MailMerge.SuppressBlankLines = true;
        wordDoc.MailMerge.Execute(false);

        // Close the input document
        wordDoc.Close(false);

        // Active document is now what?  The error document?
        // Close this too
        wordApp.ActiveDocument.Saved = true;
        wordApp.ActiveDocument.Close(false);

        // Now have reference to the new document
        wordApp.ActiveDocument.SaveAs2(outDoc, WdSaveFormat.wdFormatDocumentDefault);
        wordApp.ActiveDocument.Close(false);

        wordApp.Quit();
    }

Is there a more robust way of getting a reference to the document created by MailMerge.Execute?是否有更可靠的方法来获取对 MailMerge.Execute 创建的文档的引用?

Unfortunately, no.抱歉不行。 It would have been useful if the Execute method would return that if execution is to a new document rather than the printer or email...如果Execute方法返回,如果执行是针对新文档而不是打印机或电子邮件,那将会很有用...

What I would do is create an array/list/collection/dictionary/whatever of all currently open documents before executing the mail merge.我要做的是在执行邮件合并之前创建一个数组/列表/集合/字典/所有当前打开的文档。 Then check whether ActiveDocument is in that "list".然后检查ActiveDocument是否在该“列表”中。 If not, you've got the right one.如果没有,那你就选对了。 If it is, then loop the wordApp.Documents collection until you find one that is not in the "list".如果是,则循环wordApp.Documents集合,直到找到不在“列表”中的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM