Visual C를 사용하여 Microsoft Word를 자동화하여 새 문서를 만드는 방법 #

이 문서의 Microsoft Visual Basic .NET 버전은

요약

이 단계별 문서에서는 Microsoft Visual C# 2005 또는 Microsoft Visual C# .NET의 Automation을 사용하여 Microsoft Word에서 새 문서를 만드는 방법을 설명합니다.

샘플 코드

이 문서의 샘플 코드는 다음을 수행하는 방법을 보여 줍니다.

  • 텍스트 및 서식이 있는 단락을 삽입합니다.
  • 문서 내의 다양한 범위를 찾아 수정합니다.
  • 테이블을 삽입하고, 테이블에 서식을 지정하고, 데이터를 사용하여 테이블을 채웁니다.
  • 차트를 추가합니다.

Visual C# 2005 또는 Visual C# .NET에서 Automation을 사용하여 새 Word 문서를 만들려면 다음 단계를 수행합니다.

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

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

    참고 Visual Studio 2005에서 Visual C#프로젝트 대신 Visual C#을 클릭합니다.

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

    1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.
    2. COM 탭에서 Microsoft Word 개체 라이브러리를 찾은 다음 선택을 클릭합니다.

    참고 Visual Studio 2005에서는 선택을 클릭할 필요가 없습니다.

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

    1. [참조 추가] 대화 상자에서 [확인]을 클릭하여 선택 내용을 적용합니다. 선택한 라이브러리에 대한 래퍼를 생성하라는 메시지가 표시되면 [예]를 클릭합니다.
  4. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시한 다음 Form1에 단추를 추가합니다.

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

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

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

    with:

    private void button1_Click(object sender, System.EventArgs e)
    {
    object oMissing = System.Reflection.Missing.Value;
    object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
    
    //Start Word and create a new document.
    Word._Application oWord;
    Word._Document oDoc;
    oWord = new Word.Application();
    oWord.Visible = true;
    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
    ref oMissing, ref oMissing);
    
    //Insert a paragraph at the beginning of the document.
    Word.Paragraph oPara1;
    oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara1.Range.Text = "Heading 1";
    oPara1.Range.Font.Bold = 1;
    oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
    oPara1.Range.InsertParagraphAfter();
    
    //Insert a paragraph at the end of the document.
    Word.Paragraph oPara2;
    object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara2.Range.Text = "Heading 2";
    oPara2.Format.SpaceAfter = 6;
    oPara2.Range.InsertParagraphAfter();
    
    //Insert another paragraph.
    Word.Paragraph oPara3;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
    oPara3.Range.Font.Bold = 0;
    oPara3.Format.SpaceAfter = 24;
    oPara3.Range.InsertParagraphAfter();
    
    //Insert a 3 x 5 table, fill it with data, and make the first row
    //bold and italic.
    Word.Table oTable;
    Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    int r, c;
    string strText;
    for(r = 1; r <= 3; r++)
    for(c = 1; c <= 5; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Rows[1].Range.Font.Bold = 1;
    oTable.Rows[1].Range.Font.Italic = 1;
    
    //Add some text after the table.
    Word.Paragraph oPara4;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara4.Range.InsertParagraphBefore();
    oPara4.Range.Text = "And here's another table:";
    oPara4.Format.SpaceAfter = 24;
    oPara4.Range.InsertParagraphAfter();
    
    //Insert a 5 x 2 table, fill it with data, and change the column widths.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    for(r = 1; r <= 5; r++)
    for(c = 1; c <= 2; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
    oTable.Columns[2].Width = oWord.InchesToPoints(3);
    
    //Keep inserting text. When you get to 7 inches from top of the
    //document, insert a hard page break.
    object oPos;
    double dPos = oWord.InchesToPoints(7);
    oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
    do
    {
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.ParagraphFormat.SpaceAfter = 6;
    wrdRng.InsertAfter("A line of text");
    wrdRng.InsertParagraphAfter();
    oPos = wrdRng.get_Information
                           (Word.WdInformation.wdVerticalPositionRelativeToPage);
    }
    while(dPos >= Convert.ToDouble(oPos));
    object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    object oPageBreak = Word.WdBreakType.wdPageBreak;
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertBreak(ref oPageBreak);
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
    wrdRng.InsertParagraphAfter();
    
    //Insert a chart.
    Word.InlineShape oShape;
    object oClassType = "MSGraph.Chart.8";
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, 
    ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing);
    
    //Demonstrate use of late bound oChart and oChartApp objects to
    //manipulate the chart object with MSGraph.
    object oChart;
    object oChartApp;
    oChart = oShape.OLEFormat.Object;
    oChartApp = oChart.GetType().InvokeMember("Application",
    BindingFlags.GetProperty, null, oChart, null);
    
    //Change the chart type to Line.
    object[] Parameters = new Object[1];
    Parameters[0] = 4; //xlLine = 4
    oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
    null, oChart, Parameters);
    
    //Update the chart image and quit MSGraph.
    oChartApp.GetType().InvokeMember("Update",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    oChartApp.GetType().InvokeMember("Quit",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    //... If desired, you can proceed from here using the Microsoft Graph 
    //Object model on the oChart and oChartApp objects to make additional
    //changes to the chart.
    
    //Set the width of the chart.
    oShape.Width = oWord.InchesToPoints(6.25f);
    oShape.Height = oWord.InchesToPoints(3.57f);
    
    //Add text after the chart.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.InsertParagraphAfter();
    wrdRng.InsertAfter("THE END.");
    
    //Close this form.
    this.Close();
    }
    
  7. 코드 창의 맨 위로 스크롤합니다. using 지시문 목록의 끝에 다음 줄을 추가합니다.

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

  9. Button1을 클릭하여 Word 자동화를 시작하고 문서를 만듭니다.

코드가 완료되면 만들어진 문서를 검사합니다. 문서에는 서식이 지정된 단락, 표 및 차트의 두 페이지가 포함되어 있습니다.

템플릿 사용

Automation을 사용하여 모두 공통 형식의 문서를 빌드하는 경우 미리 서식이 지정된 템플릿을 기반으로 하는 새 문서로 프로세스를 시작하는 것이 도움이 될 수 있습니다. Word Automation 클라이언트에서 서식 파일을 사용하면 아무 작업도 수행하지 않은 문서 작성에 비해 두 가지 중요한 이점이 있습니다.

  • 문서 전체에서 개체의 서식 및 배치를 보다 세게 제어할 수 있습니다.
  • 적은 코드로 문서를 빌드할 수 있습니다.

서식 파일을 사용하면 문서 내의 표, 단락 및 기타 개체의 배치를 미세 조정할 수 있으며 해당 개체의 서식을 포함할 수 있습니다. Automation을 사용하면 다음과 같은 코드를 사용하여 템플릿을 기반으로 새 문서를 만들 수 있습니다.

object oTemplate = "c:\\MyTemplate.dot";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
ref oMissing, ref oMissing);

템플릿에서 다음과 같이 Automation 클라이언트가 문서의 특정 위치에 변수 텍스트를 입력할 수 있도록 책갈피를 정의할 수 있습니다.

object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

템플릿을 사용하는 또 다른 이점은 다음과 같이 런타임에 적용할 서식 스타일을 만들고 저장할 수 있다는 것입니다.

object oStyleName = "MyStyle";
oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

또는

object oStyleName = "MyStyle";
oWord.Selection.set_Style(ref oStyleName);

참조

자세한 내용은 Microsoft 기술 자료의 문서를 참조하세요.