Microsoft Word automatiseren om afdruk samenvoegen uit te voeren met Visual C++ en MFC
Samenvatting
In dit artikel wordt gedemonstreerd hoe u een Microsoft Word-document maakt en bewerkt met automation van Microsoft Visual C++ en Microsoft Foundation Classes (MFC).
Meer informatie
Dit artikel is een parallel met een Microsoft Knowledge Base-artikel waarin hetzelfde proces wordt beschreven met behulp van Microsoft Visual Basic.
Het automatiseringsvoorbeeld bouwen
Start met Microsoft Developer Studio een nieuw project 'MFC AppWizard (exe)' met de naam 'AutoProject'.
Kies in stap 1 van de MFC AppWizard 'Dialoogvenster gebaseerd' voor het toepassingstype en klik vervolgens op Voltooien.
Het dialoogvenster Nieuwe projectgegevens wordt weergegeven en geeft aan dat de klassen die moeten worden gemaakt, zijn:
Application: CAutoProjectApp in AutoProject.h and AutoProject.cpp Dialog: CAutoProjectDlg in AutoProject.h and AutoProjectDlg.cpp
Klik op OK om het project te maken.
Het dialoogvenster 'IDD_AUTOPROJECT_DIALOG' wordt geopend in het ontwerp-/bewerkingsgebied van Visual Studio. Wijzig deze volgens de instructies in de volgende twee stappen.
Verwijder het besturingselement Label (IDC_STATIC) en de knop Annuleren (IDCANCEL).
Wijzig de naam van de knop OK in 'IDRUN' en het bijschrift in 'Uitvoeren'. Sluit het ontwerpformulier voor het dialoogvenster AutoProject.rc.
Klik op ClassWizard in het menu Beeld (of druk op Ctrl+W).
Selecteer het tabblad Berichtenoverzichten. Selecteer IDRUN in de keuzelijst Object-id's en selecteer 'BN_CLICKED' in de berichtenlijst. Klik op Functie toevoegen en accepteer de functienaam 'OnRun'. Klik op OK om de ClassWizard te sluiten.
OPMERKING:** Met deze stap wordt een declaratie voor het functielid 'OnRun();' toegevoegd aan het headerbestand met de naam AutoProjectDLG.h. In deze stap wordt ook een lege skeleton message handler-functie met de naam CAutoProjectDlg::OnRun() toegevoegd aan het bestand met de naam AutoProjectDLG.cpp.
Klik op ClassWizard in het menu Beeld (of druk op Ctrl+W).
Selecteer het tabblad Automation. Klik op Klasse toevoegen en kies 'Uit een typebibliotheek'. Navigeer naar de objectbibliotheek voor de toepassing die u wilt automatiseren (als u Excel 97 automatiseert, kiest u de Objectbibliotheek van Microsoft Excel 8.0; de standaardlocatie is C:\Program Files\Microsoft Office\Office\Excel8.olb).
Als u Microsoft Excel 2000 automatiseert, kiest u Microsoft Excel 9.0 Objectbibliotheek waarvoor de standaardlocatie C:\Program Files\Microsoft Office\Office\Excel9.olb is.
Als u Microsoft Excel 2002 en Microsoft Office Excel 2003 automatiseert, wordt de objectbibliotheek ingesloten in het bestand Excel.exe. De standaardlocatie voor Excel.exe in Office 2002 is C:\program Files\Microsoft Office\Office10\Excel.exe. De standaardlocatie voor Excel.exe in Office 2003 is C:\program Files\Microsoft Office\Office11\Excel.exe. Wanneer u de juiste objectbibliotheek hebt geselecteerd, klikt u op Openen. Selecteer alle klassen in de lijst Klassen bevestigen en klik op OK.
OPMERKING Het keuzelijstvak in het dialoogvenster Klassen bevestigen bevat alle IDispatch-interfaces (die vrijwel identiek zijn aan klassen) in de Microsoft Excel-typebibliotheek. In de onderste helft van het dialoogvenster ziet u dat een implementatiebestand met de naam Excel8.cpp gegenereerde klasse wrappers bevat die zijn afgeleid van ColeDispatchDriver() en dat het juiste declaratiekopbestand Excel8.h heet. (Voor Excel 2002 en Excel 2003 hebben de bestanden de namen Excel.cpp en Excel.h.)
Opmerking Kies de juiste typebibliotheek voor de versie van Word die u automatiseert. Zie de sectie met verwijzingen hieronder voor informatie over het vinden van de juiste typebibliotheek.
Klik op OK om het dialoogvenster MFC ClassWizard te sluiten.
Voeg de volgende code toe aan de functie CAutoProjectApp::InitInstance() waarmee de COM-servicesbibliotheek wordt geladen en ingeschakeld:
BOOL CAutoProjectApp::InitInstance() { if(!AfxOleInit()) // Your addition starts here { AfxMessageBox("Could not initialize COM dll"); return FALSE; } // End of your addition AfxEnableControlContainer(); . . . }
Voeg de volgende regel toe aan de #include instructies boven aan het programmabestand AutoProject.cpp:
#include <afxdisp.h>
Voeg de include-instructie toe voor het headerbestand dat hierboven is gemaakt (msword8.h, msword9.h of msword.h) in AutoProjectDlg.cpp na de include-instructie voor stdafx.h. Een voorbeeld voor Word 97 is:
#include "stdafx.h" #include "msword8.h"
Voeg Automation-code toe aan de methode CAutoProjectDlg::OnRun, zodat deze wordt weergegeven zoals hieronder wordt weergegeven:
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); } }
Voeg de volgende code hierboven in in de code die wordt opgegeven in stap 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); }
Compileer en voer uw programma uit. Klik op de knop Uitvoeren . In Microsoft Word wordt een voorbeeldletter gestart en weergegeven. Houd er rekening mee dat sommige methoden zijn gewijzigd met Word 2000 en Word 2002. Zie de sectie Verwijzingen voor meer informatie over deze wijzigingen.
Verwijzingen
Notities voor het automatiseren van Microsoft Word 2000 en Microsoft Word 2002
Sommige methoden en eigenschappen zijn gewijzigd voor Microsoft Word 2000 en Microsoft Word 2002.
Ga voor meer informatie over Office Automation naar de ondersteuningssite van Microsoft Office Development op: Microsoft Ondersteuning