방법: Visual C# 2010 기능을 사용하여 Office Interop 개체에 액세스(C# 프로그래밍 가이드)

Visual C# 2010에는 Office API 개체에 대한 액세스를 단순화하는 새 기능이 도입되어 있습니다. 이러한 새 기능으로는 명명된 인수와 선택적 인수, dynamic이라는 새 형식이 있으며 COM 메서드의 참조 매개 변수를 값 매개 변수처럼 취급하여 인수를 전달할 수 있는 기능도 있습니다.

이 항목에서는 Microsoft Office Excel 워크시트를 만들고 표시하는 코드를 새 기능을 사용하여 작성합니다. 그런 다음 Excel 워크시트에 연결되어 있는 아이콘을 포함하는 Office Word 문서를 추가하는 코드를 작성합니다.

이 연습을 완료하려면 Microsoft Office Excel 2007 및 Microsoft Office Word 2007이 컴퓨터에 설치되어 있어야 합니다.

Windows Vista 이전의 운영 체제를 사용 중인 경우 .NET Framework 2.0이 설치되어 있어야 합니다.

참고

다음 지침처럼 컴퓨터에서 Visual Studio 사용자 인터페이스 요소 일부에 대한 이름이나 위치를 다르게 표시할 수 있습니다. 이러한 요소는 사용하는 Visual Studio 버전 및 설정에 따라 결정됩니다. 자세한 내용은 Visual Studio 설정을 참조하십시오.

새 콘솔 응용 프로그램을 만들려면

  1. Visual Studio를 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다. 새 프로젝트 대화 상자가 나타납니다.

  3. 설치된 템플릿 창에서 **Visual C#**을 확장한 다음 Windows를 클릭합니다.

  4. 새 프로젝트 대화 상자 맨 위에서 대상 프레임워크로 .NET Framework 4가 선택되어 있는지 확인합니다.

  5. 템플릿 창에서 콘솔 응용 프로그램을 클릭합니다.

  6. 이름 필드에 프로젝트 이름을 입력합니다.

  7. 확인을 클릭합니다.

    솔루션 탐색기에 새 프로젝트가 나타납니다.

참조를 추가하려면

  1. 솔루션 탐색기에서 프로젝트 이름을 마우스 오른쪽 단추로 클릭한 다음 참조 추가를 클릭합니다. 참조 추가 대화 상자가 나타납니다.

  2. .NET 페이지에 있는 구성 요소 이름 목록에서 Microsoft.Office.Interop.Word를 선택한 후 Ctrl 키를 누른 상태로 Microsoft.Office.Interop.Excel을 선택합니다.

  3. 확인을 클릭합니다.

필요한 using 지시문을 추가하려면

  1. 솔루션 탐색기에서 Program.cs 파일을 마우스 오른쪽 단추로 클릭하고 코드 보기를 클릭합니다.

  2. 코드 파일의 맨 위에 다음 using 지시문을 추가합니다.

    using Excel = Microsoft.Office.Interop.Excel;
    using Word = Microsoft.Office.Interop.Word;
    

은행 계정 목록을 만들려면

  1. 다음 클래스 정의를 Program.cs에서 Program 클래스 아래에 붙여 넣습니다.

    public class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
    }
    
  2. 다음 코드를 Main 메서드에 추가하여 두 계정을 포함하는 bankAccounts 목록을 만듭니다.

    // Create a list of accounts.
    var bankAccounts = new List<Account> {
        new Account { 
                      ID = 345678,
                      Balance = 541.27
                    },
        new Account {
                      ID = 1230221,
                      Balance = -127.44
                    }
    };
    

계정 정보를 Excel로 내보내는 메서드를 선언하려면

  1. Program 클래스에 다음 메서드를 추가하여 Excel 워크시트를 설정합니다.

    Add 메서드에는 특정 템플릿을 지정하기 위한 선택적 매개 변수가 있습니다. 이 선택적 매개 변수는 Visual C# 2010에 새로 도입되었으며 매개 변수의 기본값을 사용하려면 매개 변수에 대한 인수를 생략하면 됩니다. 다음 코드의 경우 인수가 전달되지 않기 때문에 Add에서는 기본 템플릿을 사용하여 새 통합 문서를 만듭니다. 이와 동등한 문을 이전 버전의 C#으로 작성하려면 자리 표시자 매개 변수 ExcelApp.Workbooks.Add(Type.Missing)가 필요합니다.

    static void DisplayInExcel(IEnumerable<Account> accounts)
    {
        var excelApp = new Excel.Application();
        // Make the object visible.
        excelApp.Visible = true;
    
        // Create a new, empty workbook and add it to the collection returned 
        // by property Workbooks. The new workbook becomes the active workbook.
        // Add has an optional parameter for specifying a praticular template. 
        // Because no argument is sent in this example, Add creates a new workbook. 
        excelApp.Workbooks.Add();
    
        // This example uses a single workSheet. The explicit type casting is
        // removed in a later procedure.
        Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
    }
    
  2. DisplayInExcel의 끝 부분에 다음 코드를 추가합니다. 이 코드는 워크시트의 첫 번째 행에 있는 처음 두 열에 값을 삽입합니다.

    // Establish column headings in cells A1 and B1.
    workSheet.Cells[1, "A"] = "ID Number";
    workSheet.Cells[1, "B"] = "Current Balance";
    
  3. DisplayInExcel의 끝 부분에 다음 코드를 추가합니다. foreach 루프는 계정 목록에서 정보를 가져와 워크시트의 다음 행들에 있는 처음 두 열에 삽입합니다.

    
    var row = 1;
    foreach (var acct in accounts)
    {
        row++;
        workSheet.Cells[row, "A"] = acct.ID;
        workSheet.Cells[row, "B"] = acct.Balance;
    }
    
  4. DisplayInExcel의 끝에 다음 코드를 추가하여 내용에 맞게 열 너비를 조정합니다.

    workSheet.Columns[1].AutoFit();
    workSheet.Columns[2].AutoFit();
    

    이전 버전의 C#으로 이러한 작업을 수행하려면 AutoFit이 Excel Range 메서드이기 때문에 ExcelApp.Columns[1]에서 반환하는 Object를 명시적으로 캐스팅해야 합니다. 다음 줄은 이 캐스팅에 대해 보여 줍니다.

    ((Excel.Range)workSheet.Columns[1]).AutoFit();
    ((Excel.Range)workSheet.Columns[2]).AutoFit();
    

    Visual C# 2010에서는 해당 어셈블리가 /link 컴파일러 옵션에 의해 참조되거나 Interop 형식 포함 속성이 true로 설정되어 있으면 반환되는 Object를 dynamic으로 자동 변환합니다. 이 속성의 기본값은 true입니다.

프로젝트를 실행하려면

  1. Main의 끝부분에 다음 줄을 추가합니다.

    // Display the list in an Excel spreadsheet.
    DisplayInExcel(bankAccounts);
    
  2. Ctrl+F5를 누릅니다.

    두 계정의 데이터를 포함하는 Excel 워크시트가 나타납니다.

Word 문서를 추가하려면

  1. 다음 코드에서는 Word 응용 프로그램을 열고 Excel 워크시트에 연결되는 아이콘을 만들어 봄으로써 Visual C# 2010에서 개선된 Office 프로그래밍의 다른 측면을 살펴봅니다.

    CreateIconInWordDoc 메서드를 Program 클래스에 붙여 넣습니다. 이 메서드는 이 단계의 뒷부분에서 제공됩니다. CreateIconInWordDoc에서는 명명된 인수와 선택적 인수를 사용하므로 AddPasteSpecial에 대한 메서드 호출의 복잡성이 줄어듭니다. 이러한 메서드 호출은 Visual C# 2010의 두 가지 새로운 다른 기능을 통합하여 참조 매개 변수를 가지는 COM 메서드에 대한 호출을 단순화합니다. 첫 번째 기능은 참조 매개 변수를 값 매개 변수처럼 취급하여 해당 매개 변수에 인수를 전달하는 것입니다. 즉, 각 참조 매개 변수에 대한 변수를 만들지 않고 참조 매개 변수에 값을 직접 전달할 수 있습니다. 컴파일러에서는 인수 값을 저장하기 위해 임시 변수를 생성하고 메서드 호출에서 되돌아올 때 이 변수를 삭제합니다. 두 번째 기능은 인수 목록에서 ref 키워드를 생략하는 것입니다.

    Add 메서드의 경우 참조 매개 변수 4개가 있고 이들 모두 선택적 매개 변수입니다. Visual C# 2010에서는 이 매개 변수 4개 중 일부 또는 모두에 대해 인수를 생략하고 기본값을 사용할 수 있습니다. Visual C# 2008 및 이전 버전의 경우 각 매개 변수에 대해 인수가 제공되어야 하며, 매개 변수 4개가 참조 매개 변수이므로 인수는 변수여야 합니다.

    PasteSpecial 메서드에서는 클립보드의 내용을 삽입합니다. 이 메서드의 경우 참조 매개 변수 7개가 있고 이들 모두 선택적 매개 변수입니다. 다음 코드에서는 매개 변수 7개 중 2개에 대해 인수를 지정합니다. 즉, 클립보드 내용의 소스에 대한 링크를 만들기 위해 Link에 대한 인수를 지정하고, 링크를 아이콘으로 표시하기 위해 DisplayAsIcon에 대한 인수를 지정합니다. Visual C# 2010에서는 이 두 매개 변수에 대해 명명된 인수를 사용하고 나머지 매개 변수에 대한 인수는 생략할 수 있습니다. 이러한 매개 변수가 참조 매개 변수이기는 하지만 ref 키워드를 사용하거나 변수를 만들어 인수로 전달할 필요는 없습니다. 값을 직접 전달하면 됩니다. Visual C# 2008 및 이전 버전에서는 각 참조 매개 변수에 대한 인수로 변수를 전달해야 합니다.

    static void CreateIconInWordDoc()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    
        // The Add method has four reference parameters, all of which are 
        // optional. Visual C# 2010 allows you to omit arguments for them if
        // the default values are what you want.
        wordApp.Documents.Add();
    
        // PasteSpecial has seven reference parameters, all of which are 
        // optional. This example uses named arguments to specify values 
        // for two of the parameters. Although these are reference 
        // parameters, you do not need to use the ref keyword, or to create 
        // variables to send in as arguments. You can send the values directly.
        wordApp.Selection.PasteSpecial( Link: true, DisplayAsIcon: true);
    }
    

    이 언어의 Visual C# 2008 또는 이전 버전에서는 보다 복잡한 다음과 같은 코드가 필요합니다.

    static void CreateIconInWordDoc2008()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    
        // The Add method has four parameters, all of which are optional. 
        // In Visual C# 2008 and earlier versions, an argument has to be sent 
        // for every parameter. Because the parameters are reference  
        // parameters of type object, you have to create an object variable
        // for the arguments that represents 'no value'. 
    
        object useDefaultValue = Type.Missing;
    
        wordApp.Documents.Add(ref useDefaultValue, ref useDefaultValue,
            ref useDefaultValue, ref useDefaultValue);
    
        // PasteSpecial has seven reference parameters, all of which are
        // optional. In this example, only two of the parameters require
        // specified values, but in Visual C# 2008 an argument must be sent
        // for each parameter. Because the parameters are reference parameters,
        // you have to contruct variables for the arguments.
        object link = true;
        object displayAsIcon = true;
    
        wordApp.Selection.PasteSpecial( ref useDefaultValue,
                                        ref link,
                                        ref useDefaultValue,
                                        ref displayAsIcon,
                                        ref useDefaultValue,
                                        ref useDefaultValue,
                                        ref useDefaultValue);
    }
    
  2. Main의 끝부분에 다음 문을 추가합니다.

    // Create a Word document that contains an icon that links to
    // the spreadsheet.
    CreateIconInWordDoc();
    
  3. DisplayInExcel의 끝부분에 다음 문을 추가합니다. Copy 메서드에서는 클립보드에 워크시트를 추가합니다.

    // Put the spreadsheet contents on the clipboard. The Copy method has one
    // optional parameter for specifying a destination. Because no argument  
    // is sent, the destination is the Clipboard.
    workSheet.Range["A1:B3"].Copy();
    
  4. Ctrl+F5를 누릅니다.

    아이콘을 포함하는 Word 문서가 나타납니다. 아이콘을 두 번 클릭하여 워크시트를 포그라운드로 가져옵니다.

Interop 형식 포함 속성을 설정하려면

  1. 또 다른 개선 사항은 런타임에 PIA(주 interop 어셈블리)가 필요하지 않은 COM 형식을 호출할 때 확인할 수 있습니다. PIA에 대한 종속성이 제거되면 버전에 종속되지 않고 배포가 쉬워집니다. PIA 없이 프로그래밍할 경우의 이점에 대한 자세한 내용은 연습: 관리되는 어셈블리의 형식 포함(C# 및 Visual Basic)을 참조하십시오.

    또한 COM 메서드에서 필요한 형식 및 반환하는 형식을 Object 대신 dynamic 형식을 사용하여 나타낼 수 있으므로 프로그래밍이 더 쉬워집니다. 형식이 dynamic인 변수는 런타임 이전에 계산되지 않으므로 명시적 캐스팅이 필요하지 않습니다. 자세한 내용은 dynamic 형식 사용(C# 프로그래밍 가이드)을 참조하십시오.

    Visual C# 2010에서의 기본 동작은 PIA를 사용하는 대신 형식 정보를 포함하는 것입니다. 이러한 기본 동작 때문에 명시적 캐스팅이 필요하지 않으므로 앞의 일부 예제를 단순화할 수 있습니다. 예를 들어, DisplayInExcel에서의 worksheet 선언은 Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet 대신 Excel._Worksheet workSheet = excelApp.ActiveSheet로 작성됩니다. 이 기본 동작이 없으면 동일한 메서드에서 AutoFit에 대한 호출에도 명시적 캐스팅이 필요합니다. ExcelApp.Columns[1]에서 Object를 반환하지만 AutoFit은 Excel 메서드이기 때문입니다. 다음 코드에서는 이러한 캐스팅을 보여 줍니다.

    ((Excel.Range)workSheet.Columns[1]).AutoFit();
    ((Excel.Range)workSheet.Columns[2]).AutoFit();
    
  2. 기본 동작을 변경하여 형식 정보를 포함하는 대신 PIA를 사용하려면 솔루션 탐색기에서 참조 노드를 확장한 다음 Microsoft.Office.Interop.Excel 또는 Microsoft.Office.Interop.Word를 선택합니다.

  3. 속성 창이 표시되지 않으면 F4 키를 누르십시오.

  4. 속성 목록에서 Interop 형식 포함을 찾은 후 값을 False로 변경합니다. 또는 명령 프롬프트에서 컴파일러 옵션으로 /link 대신 /reference를 사용하여 컴파일할 수도 있습니다.

표에 서식을 추가하려면

  1. DisplayInExcel에서 AutoFit에 대한 두 가지 호출을 다음 문으로 바꿉니다.

    // Call to AutoFormat in Visual C# 2010.
    workSheet.Range["A1", "B3"].AutoFormat(
        Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
    

    AutoFormat 메서드에는 값 매개 변수 7개가 있고 이들 매개 변수는 모두 선택적입니다. 명명된 선택적 매개 변수 7개에 대해 인수를 전혀 제공하지 않거나 일부 또는 모든 매개 변수에 인수를 제공할 수 있습니다. 위의 문에서는 매개 변수 중 단 하나, 즉 Format에 대해서만 인수가 제공됩니다. Format은 매개 변수 목록에서 첫 번째 매개 변수이므로 이 매개 변수의 이름은 제공하지 않아도 됩니다. 그러나 다음 코드와 같이 매개 변수 이름이 포함되어 있으면 문을 보다 쉽게 이해할 수 있습니다.

    // Call to AutoFormat in Visual C# 2010.
    workSheet.Range["A1", "B3"].AutoFormat(Format:
        Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
    
  2. Ctrl+F5를 눌러 결과를 확인합니다. 다른 서식이 XlRangeAutoFormat 열거형에 나열됩니다.

  3. 1단계에서 제공한 문을 다음 코드와 비교합니다. 이 코드에서는 Visual C# 2008 또는 이전 버전에서 필요한 인수를 보여 줍니다.

    // The AutoFormat method has seven optional value parameters. The
    // following call specifies a value for the first parameter, and uses 
    // the default values for the other six. 
    
    // Call to AutoFormat in Visual C# 2008. This code is not part of the
    // current solution.
    excelApp.get_Range("A1", "B4").AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatTable3, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing);
    

예제

다음 코드에서는 전체 예제를 보여 줍니다.

using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;


namespace OfficeProgramminWalkthruComplete
{
    class Walkthrough
    {
        static void Main(string[] args)
        {
            // Create a list of accounts.
            var bankAccounts = new List<Account> 
            {
                new Account { 
                              ID = 345678,
                              Balance = 541.27
                            },
                new Account {
                              ID = 1230221,
                              Balance = -127.44
                            }
            };

            // Display the list in an Excel spreadsheet.
            DisplayInExcel(bankAccounts);

            // Create a Word document that contains an icon that links to
            // the spreadsheet.
            CreateIconInWordDoc();
        }

        static void DisplayInExcel(IEnumerable<Account> accounts)
        {
            var excelApp = new Excel.Application();
            // Make the object visible.
            excelApp.Visible = true;

            // Create a new, empty workbook and add it to the collection returned 
            // by property Workbooks. The new workbook becomes the active workbook.
            // Add has an optional parameter for specifying a praticular template. 
            // Because no argument is sent in this example, Add creates a new workbook. 
            excelApp.Workbooks.Add();

            // This example uses a single workSheet. 
            Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // Earlier versions of C# require explicit casting.
            //Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

            // Establish column headings in cells A1 and B1.
            workSheet.Cells[1, "A"] = "ID Number";
            workSheet.Cells[1, "B"] = "Current Balance";

            var row = 1;
            foreach (var acct in accounts)
            {
                row++;
                workSheet.Cells[row, "A"] = acct.ID;
                workSheet.Cells[row, "B"] = acct.Balance;
            }

            workSheet.Columns[1].AutoFit();
            workSheet.Columns[2].AutoFit();

            // Call to AutoFormat in Visual C# 2010. This statement replaces the 
            // two calls to AutoFit.
            workSheet.Range["A1", "B3"].AutoFormat(
                Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);

            // Put the spreadsheet contents on the clipboard. The Copy method has one
            // optional parameter for specifying a destination. Because no argument  
            // is sent, the destination is the Clipboard.
            workSheet.Range["A1:B3"].Copy();
        }

        static void CreateIconInWordDoc()
        {
            var wordApp = new Word.Application();
            wordApp.Visible = true;

            // The Add method has four reference parameters, all of which are 
            // optional. Visual C# 2010 allows you to omit arguments for them if
            // the default values are what you want.
            wordApp.Documents.Add();

            // PasteSpecial has seven reference parameters, all of which are 
            // optional. This example uses named arguments to specify values 
            // for two of the parameters. Although these are reference 
            // parameters, you do not need to use the ref keyword, or to create 
            // variables to send in as arguments. You can send the values directly.
            wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
        }
    }

    public class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
    }
}

참고 항목

작업

방법: Office 프로그래밍에 명명된 인수와 선택적 인수 사용(C# 프로그래밍 가이드)

참조

dynamic(C# 참조)

Type.Missing

개념

명명된 인수와 선택적 인수(C# 프로그래밍 가이드)

기타 리소스

dynamic 형식 사용(C# 프로그래밍 가이드)