如何使用 Visual C++ 和 MFC 自动执行 Microsoft Word 以执行邮件合并

摘要

本文演示如何使用来自 Microsoft Visual C++ 和 Microsoft Foundation Classes (MFC) 的自动化创建和操作 Microsoft Word 文档。

更多信息

本文与 Microsoft 知识库文章并行,该文章介绍使用 Microsoft Visual Basic 的相同过程。

生成自动化示例

  1. 使用 Microsoft Developer Studio,启动名为“AutoProject”的新“MFC AppWizard (exe) ”项目。

  2. 在 MFC AppWizard 的步骤 1 中,为应用程序类型选择“基于对话框”,然后单击“完成”。

    将显示“新建项目信息”对话框,并指示要创建的类包括:

    Application: CAutoProjectApp in AutoProject.h and AutoProject.cpp
    Dialog: CAutoProjectDlg in AutoProject.h and AutoProjectDlg.cpp
    

    单击“确定”以创建项目。

  3. “IDD_AUTOPROJECT_DIALOG”对话框将在 Visual Studio 设计/编辑区域中打开。 根据后续两个步骤中的说明对其进行修改。

  4. 删除 IDCANCEL) (标签控件 (IDC_STATIC) 和“取消”按钮。

  5. 将“确定”按钮的名称更改为“IDRUN”,将标题更改为“运行”。关闭 AutoProject.rc 对话框设计窗体。

  6. 单击“视图”菜单上的 ClassWizard (或按 Ctrl+W) 。

  7. 选择“消息地图”选项卡。在“对象 ID”列表框中选择 IDRUN,然后在“消息”列表框中选择“BN_CLICKED”。 单击“添加函数”并接受函数名称“OnRun”。 单击“确定”关闭 ClassWizard。

    注意:** 此步骤向名为 AutoProjectDLG.h 的标头文件添加函数成员“OnRun () ;”的声明。 此步骤还会将名为 CAutoProjectDlg::OnRun () 的空主干消息处理程序函数添加到名为 AutoProjectDLG.cpp 的文件中。

  8. 单击“视图”菜单上的 ClassWizard (或按 Ctrl+W) 。

  9. 选择“自动化”选项卡。单击“添加类”,然后选择“从类型库中”。导航以选择要自动执行此示例 (的应用程序的对象库,如果要自动执行 Excel 97,请选择 Microsoft Excel 8.0 对象库;默认位置为 C:\Program Files\Microsoft Office\Office\Excel8.olb) 。

    如果要自动执行 Microsoft Excel 2000,请选择默认位置为 C:\Program Files\Microsoft Office\Office\Excel9.olb 的 Microsoft Excel 9.0 对象库。

    如果要自动执行 Microsoft Excel 2002 和 Microsoft Office Excel 2003,则对象库将嵌入到文件Excel.exe中。 Office 2002 中Excel.exe的默认位置是 C:\program Files\Microsoft Office\Office10\Excel.exe。 Office 2003 中Excel.exe的默认位置是 C:\program Files\Microsoft Office\Office11\Excel.exe。 选择相应的对象库后,单击“打开”。 选择“确认类”列表中的所有类,然后单击“确定”。

    注意 “确认类”对话框中的列表框包含所有 IDispatch 接口 (这些接口几乎与 Microsoft Excel 类型库中) 的类相同。 在对话框的下半部分,你会看到名为 Excel8.cpp 的实现文件包含派生自 ColeDispatchDriver () 的生成的类包装器,相应的声明标头文件名为 Excel8.h。 (对于 Excel 2002 和 Excel 2003,这些文件名为 Excel.cpp 和 Excel.h.)

    注意 为要自动执行的 Word 版本选择正确的类型库。 有关查找正确类型库的信息,请参阅下面的“参考”部分。

  10. 单击“确定”关闭 MFC ClassWizard 对话框。

  11. 将以下代码添加到 CAutoProjectApp::InitInstance () 函数,该函数加载并启用 COM 服务库:

    BOOL CAutoProjectApp::InitInstance()
      {
         if(!AfxOleInit())  // Your addition starts here
         {
            AfxMessageBox("Could not initialize COM dll");
            return FALSE;
         }                 // End of your addition
    
         AfxEnableControlContainer();
      .
      .
      .
    
      }
    
  12. 将以下行添加到 AutoProject.cpp 程序文件顶部的#include语句:

      #include <afxdisp.h>
    
  13. 在 stdafx.h 的 include 语句之后,添加在 AutoProjectDlg.cpp 中创建的头文件的 include 语句 (msword8.h、msword9.h 或 msword.h) 。 Word 97 的一个示例是:

       #include "stdafx.h"
       #include "msword8.h"
    
    
  14. 将自动化代码添加到 CAutoProjectDlg::OnRun 方法,使其如下所示:

    void CAutoProjectDlg::OnRun()
    {
    _Application oWord;
    Documents oDocs;
    _Document oDoc;
    Selection oSelection;
    Paragraphs oParagraphs;
    Tables oTables;
    Table oTable;
    Range oRange;
    Columns oColumns;
    Column oColumn;
    Rows oRows;
    Row oRow;
    
    Cells oCells;
    Cell oCell; 
    Shading oShading;
    Hyperlinks oHyperlinks;
    MailMerge oMailMerge;
    MailMergeFields oMailMergeFields;
    COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
            vtTrue((short)TRUE),
    vtFalse((short)FALSE);
    CString StrToAdd;
    
    // Create an instance of Word
    if (!oWord.CreateDispatch("Word.Application")) {
    AfxMessageBox("Word failed to start!");
    } else {
    // Set the visible property
    oWord.SetVisible(TRUE);
    // Add a new document
    oDocs = oWord.GetDocuments();
    oDoc = oDocs.Add(vtOptional,vtOptional);
    
    CreateMailMergeDataFile(&oWord,&oDoc);
    // Add the address header
    
    StrToAdd = "State University\r\nElectrical Engineering " \ 
           "Department";
    oSelection = oWord.GetSelection();
    
    oParagraphs = oSelection.GetParagraphs();
    oParagraphs.SetAlignment(1);  // 1 = wdAlignParagraphCenter  
    oSelection.TypeText(StrToAdd);
    
    InsertLines(&oSelection,4);
    
    oParagraphs.SetAlignment(0);  // 0 = wdAlignParagraphLeft
    oMailMerge = oDoc.GetMailMerge();
    oMailMergeFields = oMailMerge.GetFields();
    oMailMergeFields.Add(oSelection.GetRange(),"FirstName");
    oSelection.TypeText(" ");
    oMailMergeFields.Add(oSelection.GetRange(),"LastName");
    oSelection.TypeParagraph();
    oMailMergeFields.Add(oSelection.GetRange(),"Address");
    oSelection.TypeParagraph();
    oMailMergeFields.Add(oSelection.GetRange(),"CityStateZip");
    
    InsertLines(&oSelection,4);
    // Set the paragraph alignment to Right justified
    oParagraphs = oSelection.GetParagraphs();
    
    oParagraphs.SetAlignment(2);  // 2 = wdAlignParagraphRight
    // Insert the current date
    oSelection.InsertDateTime(COleVariant("dddd, MMMM dd, yyyy"),\ 
     vtFalse,vtOptional);
    
    InsertLines(&oSelection,2);
    
    // Reset the justification to Justify
    
    oParagraphs = oSelection.GetParagraphs();
    oParagraphs.SetAlignment(3);  // 3 = wdAlignParagraphJustify
    
    oSelection.TypeText("Dear ");
    oMailMergeFields.Add(oSelection.GetRange(),"FirstName");
    oSelection.TypeText(",");
    
    InsertLines(&oSelection,2);
    
    // Add the body of the message
    StrToAdd = "Thank you for your recent request for next " \ 
           "semester's class schedule for the Electrical " \ 
           "Engineering Department.  Enclosed with this letter " \ 
           "is a booklet containing all the classes offered " \ 
           "next semester at State University.  Several new " \ 
           "classes will be offered in the Electrical " \ 
              "Engineering Department next semester.  These " \ 
           "classes are listed below.";
    oSelection.TypeText(StrToAdd);
    
    InsertLines(&oSelection,2);
    
    // Add a new table with 9 rows and 4 columns
    oRange = oSelection.GetRange();
    oTables = oDoc.GetTables();
    oTable = oTables.Add(oRange,9,4);
    
    // Set the width of each column
    oColumns = oTable.GetColumns();
    oColumn = oColumns.Item(1);
    oColumn.SetWidth(51.0,0);  // 0 = wdAdjustNone
    oColumn = oColumns.Item(2);
    oColumn.SetWidth(198.0,0);  // 0 = wdAdjustNone
    oColumn = oColumns.Item(3);
    oColumn.SetWidth(100.0,0);  // 0 = wdAdjustNone
    oColumn = oColumns.Item(4);
    oColumn.SetWidth(111.0,0);  // 0 = wdAdjustNone
    
    // Set the shading for row 1 to wdGray25
    oRows = oTable.GetRows();
    oRow = oRows.Item(1);
    oCells = oRow.GetCells();
    oShading = oCells.GetShading();
    oShading.SetBackgroundPatternColorIndex(16); // 16 = wdGray25
    
    // Turn on BOLD for the first row
    oRange = oRow.GetRange();
    oRange.SetBold(TRUE);
    
    // Set the alignment for cell (1,1) to center
    oCell = oTable.Cell(1,1);
    oRange = oCell.GetRange();
    oParagraphs = oRange.GetParagraphs();
    oParagraphs.SetAlignment(1);  // 1 = wdAlignParagraphCenter
    
    // Fill in the class schedule data
    FillRow(&oTable,1,"Class Number","Class Name",\ 
    "Class Time","Instructor");
    FillRow(&oTable,2, "EE220", "Introduction to Electronics II", \ 
    "1:00-2:00 M,W,F", "Dr. Jensen");
    FillRow(&oTable,3, "EE230", "Electromagnetic Field Theory I", \ 
    "10:00-11:30 T,T", "Dr. Crump");
    FillRow(&oTable,4, "EE300", "Feedback Control Systems", \ 
    "9:00-10:00 M,W,F", "Dr. Murdy");
    FillRow(&oTable,5, "EE325", "Advanced Digital Design", \ 
    "9:00-10:30 T,T", "Dr. Alley");
    FillRow(&oTable,6, "EE350", "Advanced Communication Systems", \ 
    "9:00-10:30 T,T", "Dr. Taylor");
    FillRow(&oTable,7, "EE400", "Advanced Microwave Theory", \ 
    "1:00-2:30 T,T", "Dr. Lee");
    FillRow(&oTable,8, "EE450", "Plasma Theory", \ 
    "1:00-2:00 M,W,F", "Dr. Davis");
    FillRow(&oTable,9, "EE500", "Principles of VLSI Design", \ 
    "3:00-4:00 M,W,F", "Dr. Ellison");
    
    // Go to the end of the document
    oSelection.GoTo(COleVariant((short)3), // 3 = wdGoToLine
    COleVariant((short)-1),vtOptional,vtOptional);  // -1 = wdGoToLast
    
    InsertLines(&oSelection,2);
    
    // Add closing text
    StrToAdd = "For additional information regarding the " \ 
                 "Department of Electrical Engineering, " \ 
                 "you can visit our website at ";
    oSelection.TypeText(StrToAdd);
    
    // Add a hyperlink to the homepage
    oHyperlinks = oSelection.GetHyperlinks();
    oHyperlinks.Add(oSelection.GetRange(),\ 
    COleVariant("http://www.ee.stateu.tld"),vtOptional);
    
    // Finish adding closing text
    StrToAdd = ".  Thank you for your interest in the classes " \ 
                 "offered in the Department of Electrical " \ 
                 "Engineering.  If you have any other questions, " \ 
                 "please feel free to give us a call at (999) " \ 
                 "555-1212.\r\n\r\n" \ 
                 "Sincerely,\r\n\r\n" \ 
                 "Kathryn M. Hinsch\r\n" \ 
                 "Department of Electrical Engineering\r\n";
    oSelection.TypeText(StrToAdd);
    
    // Perform mail merge
    oMailMerge.SetDestination(0); // 0 = wdSendToNewDocument
    oMailMerge.Execute(vtFalse);
    
    // Close the original form document
    oDoc.SetSaved(TRUE);
    oDoc.Close(vtFalse,vtOptional,vtOptional);
    
    }
    }
    
    
  15. 在步骤 3 中给出的代码中插入上述代码:

    void InsertLines(Selection *pSelection, int NumLines)
    {
    int iCount;
    
    // Insert NumLines blank lines
    for (iCount = 1; iCount <= NumLines; iCount++)
    pSelection->TypeParagraph();
    }
    
    void FillRow(Table *pTable,int Row, CString Text1, 
     CString Text2, CString Text3, CString Text4)
    {
    Cell oCell;
    Range oRange;
    
    // Insert data into the specific cell
    oCell = pTable->Cell(Row,1);
    oRange = oCell.GetRange();
    oRange.InsertAfter(Text1);
    oCell = pTable->Cell(Row,2);
    oRange = oCell.GetRange();
    oRange.InsertAfter(Text2);
    oCell = pTable->Cell(Row,3);
    oRange = oCell.GetRange();
    oRange.InsertAfter(Text3);
    oCell = pTable->Cell(Row,4);
    oRange = oCell.GetRange();
    oRange.InsertAfter(Text4);
    
    }
    
    void CreateMailMergeDataFile(_Application *pApp,_Document *pDoc)
    {
      _Document oDataDoc;
      MailMerge oMailMerge;
      Documents oDocs;
      Tables oTables;
      Table oTable;
      Rows oRows;
      int iCount;
      COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
    vtFalse((short)FALSE);
    
    // Create a data source at C:\DataDoc.doc containing the field data
      oMailMerge = pDoc->GetMailMerge();
      oMailMerge.CreateDataSource(COleVariant("C:\\DataDoc.doc"), \ 
            vtOptional,vtOptional, \ 
            COleVariant("FirstName, LastName, Address,CityStateZip"),\ 
            vtOptional, vtOptional,vtOptional,vtOptional,vtOptional);
      // Open the file to insert data
      oDocs = pApp->GetDocuments();
      oDataDoc = oDocs.Open(COleVariant("C:\\DataDoc.doc"), \ 
           vtOptional,vtOptional,vtOptional,vtOptional,\ 
           vtOptional,vtOptional,vtOptional,vtOptional,\ 
           vtOptional);
      oTables = oDataDoc.GetTables();
      oTable = oTables.Item(1);
      oRows = oTable.GetRows();
      for (iCount=1; iCount<=2; iCount++)  
        oRows.Add(vtOptional);
    
    // Fill in the data
      FillRow(&oTable, 2, "Steve", "DeBroux", \ 
            "4567 Main Street", "Buffalo, NY  98052");
      FillRow(&oTable, 3, "Jan", "Miksovsky", \ 
            "1234 5th Street", "Charlotte, NC  98765");
      FillRow(&oTable, 4, "Brian", "Valentine", \ 
            "12348 78th Street  Apt. 214", "Lubbock, TX  25874");
      // Save and close the file
      oDataDoc.Save();
      oDataDoc.Close(vtFalse,vtOptional,vtOptional);
    }
    
    
  16. 编译并运行程序。 单击 “运行” 按钮,Microsoft Word 应启动并显示示例字母。 请注意,Word 2000 和 Word 2002 中某些方法已更改。 有关这些更改的详细信息,请参阅“参考”部分。

参考

有关自动执行 Microsoft Word 2000 和 Microsoft Word 2002 的说明

Microsoft Word 2000 和 Microsoft Word 2002 的某些方法和属性已更改。

有关 Office 自动化的详细信息,请访问 Microsoft Office 开发支持站点:Microsoft 支持部门