Visual C++ 및 MFC를 사용하여 편지 병합을 수행하도록 Microsoft Word를 자동화하는 방법

요약

이 문서에서는 Microsoft Visual C++ 및 MFC(Microsoft Foundation Classs)에서 Automation을 사용하여 Microsoft Word 문서를 만들고 조작하는 방법을 보여 줍니다.

추가 정보

이 문서에서는 Microsoft Visual Basic을 사용하는 동일한 프로세스를 설명하는 Microsoft 기술 자료 문서와 유사합니다.

자동화 샘플 빌드

  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. Visual Studio 디자인/편집 영역에서 "IDD_AUTOPROJECT_DIALOG" 대화 상자가 열립니다. 다음 두 단계의 지침에 따라 수정합니다.

  4. 레이블 컨트롤(IDC_STATIC) 및 취소 단추(IDCANCEL)를 제거합니다.

  5. 확인 단추의 이름을 "IDRUN"으로 변경하고 캡션을 "실행"으로 변경합니다. AutoProject.rc 대화 상자 디자인 양식을 닫습니다.

  6. 보기 메뉴에서 ClassWizard를 클릭하거나 Ctrl+W를 누릅니다.

  7. 메시지 맵 탭을 선택합니다. 개체 ID 목록 상자에서 IDRUN을 선택하고 메시지 목록 상자에서 "BN_CLICKED"을 선택합니다. 함수 추가를 클릭하고 함수 이름 "OnRun"을 적용합니다. 확인을 클릭하여 ClassWizard를 닫습니다.

    참고:** 이 단계에서는 함수 멤버 "OnRun();"에 대한 선언을 AutoProjectDLG.h라는 헤더 파일에 추가합니다. 또한 이 단계에서는 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. 적절한 개체 라이브러리를 선택한 후 열기를 클릭합니다. 클래스 확인 목록에서 모든 클래스를 선택한 다음 확인을 클릭합니다.

    참고 클래스 확인 대화 상자의 목록 상자에는 Microsoft Excel 형식 라이브러리의 모든 IDispatch 인터페이스(클래스와 거의 동일)가 포함되어 있습니다. 대화 상자의 아래쪽 절반에 Excel8.cpp라는 구현 파일에 ColeDispatchDriver()에서 파생된 생성된 클래스 래퍼가 포함되어 있으며 적절한 선언 헤더 파일의 이름은 Excel8.h입니다. (Excel 2002 및 Excel 2003의 경우 파일 이름은 Excel.cpp 및 Excel.h.)

    참고 자동화하는 Word 버전에 맞는 올바른 형식 라이브러리를 선택합니다. 올바른 형식 라이브러리를 찾는 방법에 대한 자세한 내용은 아래 참조 섹션을 참조하세요.

  10. 확인을 클릭하여 MFC ClassWizard 대화 상자를 닫습니다.

  11. COM 서비스 라이브러리를 로드하고 사용하도록 설정하는 CAutoProjectApp::InitInstance() 함수에 다음 코드를 추가합니다.

    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에서 위에서 만든 헤더 파일(msword8.h, msword9.h 또는 msword.h)에 대한 include 문을 추가합니다. Word 97의 예는 다음과 같습니다.

       #include "stdafx.h"
       #include "msword8.h"
    
    
  14. 아래와 같이 표시되도록 CAutoProjectDlg::OnRun 메서드에 Automation 코드를 추가합니다.

    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 Automation에 대한 자세한 내용은 다음의 Microsoft Office 개발 지원 사이트를 방문하세요. Microsoft 지원