Automatisieren von Microsoft Word zum Ausführen eines Seriendrucks mit Visual C++ und MFC

Zusammenfassung

In diesem Artikel wird veranschaulicht, wie Sie ein Microsoft Word-Dokument mithilfe von Automatisierung aus Microsoft Visual C++ und Microsoft Foundation Classes (MFC) erstellen und bearbeiten.

Weitere Informationen

Dieser Artikel ist parallel zu einem Microsoft Knowledge Base-Artikel, in dem der gleiche Prozess mit Microsoft Visual Basic beschrieben wird.

Erstellen des Automatisierungsbeispiels

  1. Starten Sie mit Microsoft Developer Studio ein neues Projekt "MFC AppWizard (exe)" mit dem Namen "AutoProject".

  2. Wählen Sie in Schritt 1 des MFC AppWizard für den Anwendungstyp "Dialogbasiert" aus, und klicken Sie dann auf "Fertig stellen".

    Das Dialogfeld "Neue Projektinformationen" wird angezeigt und gibt an, dass die zu erstellenden Klassen Folgendes umfassen:

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

    Klicken Sie auf OK, um das Projekt zu erstellen.

  3. Das Dialogfeld "IDD_AUTOPROJECT_DIALOG" wird im Entwurfs-/Bearbeitungsbereich von Visual Studio geöffnet. Ändern Sie sie gemäß den Anweisungen in den nächsten beiden Schritten.

  4. Entfernen Sie das Bezeichnungssteuerelement (IDC_STATIC) und die Schaltfläche "Abbrechen" (IDCANCEL).

  5. Ändern Sie den Namen der Schaltfläche "OK" in "IDRUN" und die Beschriftung in "Ausführen". Schließen Sie das Entwurfsformular für das Dialogfeld "AutoProject.rc".

  6. Klicken Sie im Menü "Ansicht" auf "ClassWizard" (oder drücken Sie STRG+W).

  7. Wählen Sie die Registerkarte "Nachrichtenzuordnungen" aus. Wählen Sie im Listenfeld "Objekt-IDs" die Option "IDRUN" und im Listenfeld "Nachrichten" die Option "BN_CLICKED" aus. Klicken Sie auf "Funktion hinzufügen", und akzeptieren Sie den Funktionsnamen "OnRun". Klicken Sie auf "OK", um den ClassWizard zu schließen.

    HINWEIS:** In diesem Schritt wird der Headerdatei "AutoProjectDLG.h" eine Deklaration für das Funktionselement "OnRun();" hinzugefügt. In diesem Schritt wird der Datei "AutoProjectDLG.cpp" auch eine leere Meldungshandlerfunktion namens "CAutoProjectDlg::OnRun()" hinzugefügt.

  8. Klicken Sie im Menü "Ansicht" auf "ClassWizard" (oder drücken Sie STRG+W).

  9. Wählen Sie die Registerkarte "Automatisierung" aus. Klicken Sie auf "Klasse hinzufügen", und wählen Sie "Aus einer Typbibliothek" aus. Navigieren Sie, um die Objektbibliothek für die Anwendung auszuwählen, die Sie automatisieren möchten (wählen Sie in diesem Beispiel, wenn Sie Excel 97 automatisieren, die Microsoft Excel 8.0-Objektbibliothek aus. Der Standardspeicherort ist "C:\Programme\Microsoft Office\Office\Excel8.olb").

    Wenn Sie Microsoft Excel 2000 automatisieren, wählen Sie die Microsoft Excel 9.0-Objektbibliothek aus, für die der Standardspeicherort "C:\Programme\Microsoft Office\Office\Excel9.olb" lautet.

    Wenn Sie Microsoft Excel 2002 und Microsoft Office Excel 2003 automatisieren, wird die Objektbibliothek in die Datei Excel.exe eingebettet. Der Standardspeicherort für Excel.exe in Office 2002 ist "C:\program Files\Microsoft Office\Office10\Excel.exe". Der Standardspeicherort für Excel.exe in Office 2003 ist "C:\program Files\Microsoft Office\Office11\Excel.exe". Nachdem Sie die entsprechende Objektbibliothek ausgewählt haben, klicken Sie auf "Öffnen". Wählen Sie alle Klassen in der Liste "Klassen bestätigen" aus, und klicken Sie dann auf "OK".

    HINWEIS Das Listenfeld im Dialogfeld "Klassen bestätigen" enthält alle IDispatch-Schnittstellen (die praktisch mit Klassen identisch sind) in der Microsoft Excel-Typbibliothek. In der unteren Hälfte des Dialogfelds sehen Sie, dass eine Implementierungsdatei mit dem Namen "Excel8.cpp" generierte Klassenwrapper enthält, die von ColeDispatchDriver() abgeleitet wurden, und die entsprechende Deklarationsheaderdatei heißt "Excel8.h". (Für Excel 2002 und Excel 2003 heißen die Dateien "Excel.cpp" und "Excel.h".)

    Hinweis Wählen Sie die richtige Typbibliothek für die Version von Word aus, die Sie automatisieren möchten. Informationen zum Suchen nach der richtigen Typbibliothek finden Sie im Abschnitt "Verweise" unten.

  10. Klicken Sie auf "OK", um das Dialogfeld "MFC ClassWizard" zu schließen.

  11. Fügen Sie der CAutoProjectApp::InitInstance()-Funktion den folgenden Code hinzu, der die COM-Dienstbibliothek lädt und aktiviert:

    BOOL CAutoProjectApp::InitInstance()
      {
         if(!AfxOleInit())  // Your addition starts here
         {
            AfxMessageBox("Could not initialize COM dll");
            return FALSE;
         }                 // End of your addition
    
         AfxEnableControlContainer();
      .
      .
      .
    
      }
    
  12. Fügen Sie die folgende Zeile zu den #include Anweisungen oben in der Programmdatei "AutoProject.cpp" hinzu:

      #include <afxdisp.h>
    
  13. Fügen Sie die include-Anweisung für die oben erstellte Headerdatei (entweder msword8.h, msword9.h oder msword.h) in AutoProjectDlg.cpp nach der include-Anweisung für "stdafx.h" hinzu. Ein Beispiel für Word 97 wäre:

       #include "stdafx.h"
       #include "msword8.h"
    
    
  14. Fügen Sie der CAutoProjectDlg::OnRun-Methode Automatisierungscode hinzu, damit er wie unten dargestellt angezeigt wird:

    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. Fügen Sie den folgenden Code oben in den Code ein, der in Schritt 3 angegeben ist:

    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. Kompilieren Und Führen Sie Ihr Programm aus. Klicken Sie auf die Schaltfläche " Ausführen ", und Microsoft Word sollte einen Beispielbuchstaben starten und anzeigen. Beachten Sie, dass sich einige Methoden mit Word 2000 und Word 2002 geändert haben. Weitere Informationen zu diesen Änderungen finden Sie im Abschnitt "Verweise".

References

Hinweise zur Automatisierung von Microsoft Word 2000 und Microsoft Word 2002

Einige Methoden und Eigenschaften wurden für Microsoft Word 2000 und Microsoft Word 2002 geändert.

Weitere Informationen zur Office-Automatisierung finden Sie auf der Supportwebsite für Microsoft Office-Entwicklung unter: Microsoft-Support