0

我正在尝试使用 .net 程序自动化邮件合并。Word 文档中有一封写给特定人员的单页信件,其中包含名为“Person”的邮件合并字段。我们的数据库有多个人,每个人的名字都必须进入信件的副本。我们希望将一页的字母一个接一个地连接起来。目前,此代码尝试使用 -name1 和 name2 的两个人。下面的代码为每个人名打开一个单独的单词实例。

        object oMissing = System.Reflection.Missing.Value;
        //CREATING OBJECTS OF WORD AND DOCUMENT
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document("C:\\Test\\AddressTemplate.docx");


        //SETTING THE VISIBILITY TO TRUE
        oWord.Visible = true;
        //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
        Object oTemplatePath = "C:\\Test\\AddressTemplate.docx";

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name1);
            }
        }

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name2);
            }
        }

问题:如何更改代码以仅打开一个 word 实例,填写 mailmerge 字段并将一个字母连接到另一个字母的末尾?

4

2 回答 2

1

If you call new Word.Application you're creating a new instance, if what you want is to create a new instance if there is none, but reuse one if there is already one open you can do the following:

        Application app;
        try
        {
            app = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
        }
        catch
        {
            app = new Application();
        }

Based on your comment i think you actually only have 1 instance of word open, it just opens both documents in different Windows (but a single application). Windows aren't the same as applications.

If you want it all in a single window you could reuse the previous document or else close it before you open a new one

于 2013-10-21T18:04:40.687 回答
0

上面罗南的代码对我有用。我每次都在做 new Application() ,添加 WINWORD 实例(我知道,应该更清楚)。我会说 C# 和 VB,但这是我在这个项目中使用的 VB 版本:

        ' Use same winword instance if there; if not, create new one
    Dim oApp As Application
    Try
        oApp = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"), Application)
    Catch ex As Exception
        ' Word not yet open; open new instance
        Try
            ' Ensure we have Word installed
            oApp = New Application()
        Catch eApp As Exception
            Throw New ApplicationException(String.Format("You must have Microsoft Word installed to run the Top Line report"))
        End Try
    End Try
    oApp.Visible = True
于 2014-05-10T23:23:12.260 回答