Microsoft Word를 자동화하여 Visual C에서 편지 병합을 수행하는 방법 #

이 문서의 Microsoft Visual Basic .NET 버전은 301656 참조하세요.

요약

이 문서에서는 Microsoft Visual C# 2005 또는 Microsoft Visual C# .NET을 사용하여 Microsoft Word를 자동화하여 편지 병합 문서를 만드는 방법을 보여 줍니다.

추가 정보

Automation은 Visual C# 2005 또는 Visual C# .NET과 같은 언어로 작성된 애플리케이션이 프로그래밍 방식으로 다른 애플리케이션을 제어할 수 있도록 하는 프로세스입니다. Word 자동화를 사용하면 새 문서 만들기, 문서에 텍스트 추가, 문서 서식 지정 등의 작업을 수행할 수 있습니다. Word 및 기타 Microsoft Office 응용 프로그램을 사용하면 사용자 인터페이스를 통해 수동으로 수행할 수 있는 거의 모든 작업을 Automation을 사용하여 프로그래밍 방식으로 수행할 수도 있습니다.

Word는 개체 모델을 통해 이 프로그래밍 기능을 노출합니다. 개체 모델은 Word의 논리적 구성 요소에 대응하는 클래스 및 메서드의 컬렉션입니다. 예를 들어 Application 개체, Document 개체 및 Paragraph 개체가 있으며 각 개체에는 Word에서 이러한 구성 요소의 기능이 포함됩니다. Visual C# 2005 또는 Visual C# .NET에서 개체 모델에 액세스하려면 형식 라이브러리에 대한 프로젝트 참조를 설정할 수 있습니다.

이 문서에서는 Visual C# .NET용 Word 형식 라이브러리에 대한 적절한 프로젝트 참조를 설정하는 방법을 보여 줍니다. Word를 자동화하는 샘플 코드를 제공합니다.

Automation 샘플 빌드

  1. Microsoft Visual Studio 2005 또는 Microsoft Visual Studio .NET을 시작합니다.

  2. [파일] 메뉴에서 [새로 만들기]를 클릭한 다음 [프로젝트]를 클릭합니다. Visual C# 프로젝트 형식에서 Windows 애플리케이션을 선택합니다. Form1은 기본적으로 만들어집니다.

  3. Visual Studio 2005의 Microsoft Word 11.0 개체 라이브러리 또는 Visual Studio .NET의 Microsoft Word 개체 라이브러리에 대한 참조를 추가합니다. 이렇게 하려면 다음과 같이 하십시오.

    1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.

    2. COM 탭에서 Microsoft Word 개체 라이브러리를 찾은 다음 선택을 클릭합니다.

      Visual Studio 2005의 COM 탭에서 Microsoft Word 11.0 개체 라이브러리를 찾습니다.

      참고 Microsoft Office 2003에는 IA(기본 Interop 어셈블리)가 포함되어 있습니다. Microsoft Office XP에는 PIA가 포함되지 않지만 다운로드할 수 있습니다.

    3. [참조 추가] 대화 상자에서 [확인]을 클릭하여 선택 내용을 적용합니다.

  4. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시한 다음 Form1에 단추를 추가합니다.

  5. Button1을 두 번 클릭합니다. 양식의 코드 창이 나타납니다.

  6. 코드 창에서 다음 코드를 바꿉

      private void button1_Click(object sender, System.EventArgs e)
      {
      }
    
    

    with:

    Word.Application wrdApp;
    Word._Document wrdDoc;
    Object oMissing = System.Reflection.Missing.Value;
    Object oFalse = false;
    
    private void InsertLines(int LineNum)
    {
    int iCount;
    
    // Insert "LineNum" blank lines.
    for(iCount = 1; iCount<=LineNum; iCount++) 
    {
    wrdApp.Selection.TypeParagraph();
    }
    }
    
    private void FillRow(Word._Document oDoc, int Row, string Text1,
    string Text2, string Text3, string Text4)
    {
    // Insert the data into the specific cell.
    oDoc.Tables[1].Cell(Row,1).Range.InsertAfter(Text1);
    oDoc.Tables[1].Cell(Row,2).Range.InsertAfter(Text2);
    oDoc.Tables[1].Cell(Row,3).Range.InsertAfter(Text3);
    oDoc.Tables[1].Cell(Row,4).Range.InsertAfter(Text4);
    }
    
    private void CreateMailMergeDataFile()
    {
    Word._Document oDataDoc;
    int iCount;
    
    Object oName = "C:\\DataDoc.doc";
    Object oHeader = "FirstName, LastName, Address, CityStateZip";
    wrdDoc.MailMerge.CreateDataSource(ref oName,ref oMissing, 
    ref oMissing,ref oHeader, ref oMissing, ref oMissing, 
    ref oMissing, ref oMissing, ref oMissing);
    
    // Open the file to insert data.
    oDataDoc = wrdApp.Documents.Open(ref oName,ref oMissing,
    ref oMissing, ref oMissing,ref oMissing,ref oMissing,
    ref oMissing,ref oMissing,ref oMissing,ref oMissing,
    ref oMissing,ref oMissing,ref oMissing,ref oMissing,
    ref oMissing/*, ref oMissing */);
    
    for (iCount=1; iCount<=2; iCount++)
    {
    oDataDoc.Tables[1].Rows.Add(ref oMissing);
    }
    // Fill in the data.
    FillRow(oDataDoc, 2, "Steve", "DeBroux", 
    "4567 Main Street", "Buffalo, NY  98052");
    FillRow(oDataDoc, 3, "Jan", "Miksovsky", 
    "1234 5th Street", "Charlotte, NC  98765");
    FillRow(oDataDoc, 4, "Brian", "Valentine", 
    "12348 78th Street  Apt. 214", 
    "Lubbock, TX  25874");
    // Save and close the file.
    oDataDoc.Save();
    oDataDoc.Close(ref oFalse, ref oMissing, ref oMissing);
    }
    
    private void button1_Click(object sender, System.EventArgs e)
    {
    Word.Selection wrdSelection;
    Word.MailMerge wrdMailMerge;
    Word.MailMergeFields wrdMergeFields;
    Word.Table wrdTable;
    string StrToAdd;
    
    // Create an instance of Word  and make it visible.
    wrdApp = new Word.Application();
    wrdApp.Visible = true;
    
    // Add a new document.
    wrdDoc = wrdApp.Documents.Add(ref oMissing,ref oMissing,
    ref oMissing,ref oMissing);
    wrdDoc.Select();
    
    wrdSelection = wrdApp.Selection;
    wrdMailMerge = wrdDoc.MailMerge;
    
    // Create a MailMerge Data file.
    CreateMailMergeDataFile();
    
    // Create a string and insert it into the document.
    StrToAdd = "State University\r\nElectrical Engineering Department";
    wrdSelection.ParagraphFormat.Alignment  = 
    Word.WdParagraphAlignment.wdAlignParagraphCenter;
    wrdSelection.TypeText(StrToAdd);
    
    InsertLines(4);
    
    // Insert merge data.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphLeft;
    wrdMergeFields = wrdMailMerge.Fields;
    wrdMergeFields.Add(wrdSelection.Range, "FirstName");
    wrdSelection.TypeText(" ");
    wrdMergeFields.Add(wrdSelection.Range, "LastName");
    wrdSelection.TypeParagraph();
    
    wrdMergeFields.Add(wrdSelection.Range, "Address");
    wrdSelection.TypeParagraph();
    wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
    
    InsertLines(2);
    
    // Right justify the line and insert a date field
    // with the current date.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphRight;
    
    Object objDate = "dddd, MMMM dd, yyyy";
    wrdSelection.InsertDateTime(ref objDate,ref oFalse,ref oMissing, 
    ref oMissing, ref oMissing);
    
    InsertLines(2);
    
    // Justify the rest of the document.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphJustify;    
    
    wrdSelection.TypeText("Dear ");
    wrdMergeFields.Add(wrdSelection.Range, "FirstName");
    wrdSelection.TypeText(",");
    InsertLines(2);
    
    // Create a string and insert it into the document.
    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.";
    wrdSelection.TypeText(StrToAdd);
    
    InsertLines(2);
    
    // Insert a new table with 9 rows and 4 columns.
    wrdTable = wrdDoc.Tables.Add(wrdSelection.Range,9,4, 
    ref oMissing, ref oMissing);
    // Set the column widths.
    wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone);
    // Set the shading on the first row to light gray.
    wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = 
    Word.WdColorIndex.wdGray25;
    // Bold the first row.
    wrdTable.Rows[1].Range.Bold = 1;
    // Center the text in Cell (1,1).
    wrdTable.Cell(1, 1).Range.Paragraphs.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
    // Fill each row of the table with data.
    FillRow(wrdDoc, 1, "Class Number", "Class Name", 
    "Class Time", "Instructor");
    FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II", 
    "1:00-2:00 M,W,F", "Dr. Jensen");
    FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", 
    "10:00-11:30 T,T", "Dr. Crump");
    FillRow( wrdDoc, 4, "EE300", "Feedback Control Systems", 
    "9:00-10:00 M,W,F", "Dr. Murdy");
    FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design", 
    "9:00-10:30 T,T", "Dr. Alley");
    FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems", 
    "9:00-10:30 T,T", "Dr. Taylor");
    FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory", 
    "1:00-2:30 T,T", "Dr. Lee");
    FillRow(wrdDoc, 8, "EE450", "Plasma Theory",
    "1:00-2:00 M,W,F", "Dr. Davis");
    FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design", 
    "3:00-4:00 M,W,F", "Dr. Ellison");
    
    // Go to the end of the document.
    Object oConst1 = Word.WdGoToItem.wdGoToLine;
    Object oConst2 = Word.WdGoToDirection.wdGoToLast;
    wrdApp.Selection.GoTo(ref oConst1,ref oConst2,ref oMissing,ref oMissing);
    InsertLines(2);
    
    // Create a string and insert it into the document.
    StrToAdd = "For additional information regarding the " +
    "Department of Electrical Engineering, " +
    "you can visit our Web site at ";
    wrdSelection.TypeText(StrToAdd);
    // Insert a hyperlink to the Web page.
    Object oAddress = "http://www.ee.stateu.tld";
    Object oRange = wrdSelection.Range;
    wrdSelection.Hyperlinks.Add(oRange, ref oAddress,ref oMissing,
    ref oMissing, ref oMissing, ref oMissing);
    // Create a string and insert it into the document
    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 " +
    "555-1212.\r\n\r\n"  +
    "Sincerely,\r\n\r\n" +
    "Kathryn M. Hinsch\r\n" +
    "Department of Electrical Engineering \r\n";
    wrdSelection.TypeText(StrToAdd);
    
    // Perform mail merge.
    wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
    wrdMailMerge.Execute(ref oFalse);
    
    // Close the original form document.
    wrdDoc.Saved = true;
    wrdDoc.Close(ref oFalse,ref oMissing,ref oMissing);
    
    // Release References.
    wrdSelection = null;
    wrdMailMerge = null;
    wrdMergeFields = null;
    wrdDoc = null;
    wrdApp = null;
    
    // Clean up temp file.
    System.IO.File.Delete("C:\\DataDoc.doc");
    } 
    
    

    참고 Visual Studio 2005에서 코드를 변경해야 합니다. 기본적으로 Visual C#은 Windows Forms 프로젝트를 만들 때 프로젝트에 하나의 양식을 추가합니다. 폼의 이름은 Form1입니다. 폼을 나타내는 두 파일의 이름은 Form1.cs 및 Form1.designer.cs입니다. Form1.cs에서 코드를 작성합니다. Form1.designer.cs 파일은 Windows Forms 디자이너가 도구 상자에서 컨트롤을 끌어서 놓아 수행한 모든 작업을 구현하는 코드를 작성하는 위치입니다.

    Visual C# 2005의 Windows Forms 디자이너에 대한 자세한 내용은 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요. 프로젝트 만들기(Visual C#)참고 Microsoft Office Word 2003에는 문서의 Open 메서드에 대한 추가 인수가 있습니다. Word 2003 PIA를 사용하는 경우 Open 메서드에 대한 추가 매개 변수에 대한 주석 표기법을 제거합니다.

  7. Form1.cs의 맨 위에 다음을 추가합니다.

    using Word = Microsoft.Office.Interop.Word;
    
    
  8. F5 키를 눌러 프로그램을 빌드하고 실행합니다.

  9. Button1을 클릭하여 Word Automation을 시작하고 편지 병합을 수행합니다.

참조

자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요. Visual Studio를 사용한 Microsoft Office Development with Visual Studio Microsoft Office Development

자세한 내용은 다음 문서 번호를 클릭하여 Microsoft 기술 자료의 문서를 확인합니다.

Visual Basic을 사용하여 Word 2002를 자동화하여 편지 병합을 만드는 방법 285332