다음을 통해 공유


방법: Visual C# 기능을 사용하여 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. 어셈블리 페이지의 구성 요소 이름 목록에서 Microsoft.Office.Interop.Word를 선택하고 Ctrl 키를 누른 상태로 Microsoft.Office.Interop.Excel을 선택합니다. 이러한 어셈블리가 보이지 않으면 어셈블리가 설치되어 있으며 표시되는지를 확인해야 할 수 있습니다(방법: Office 주 Interop 어셈블리 설치 참조).

  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#에서는 이러한 작업을 명시적으로 캐스팅해야 했습니다. ExcelApp.Columns[1]은 Object를 반환하며 AutoFit은 Excel Range 메서드이기 때문입니다. 다음 줄에는 캐스팅이 나와 있습니다.

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

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

프로젝트를 실행하려면

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

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

    두 계좌의 데이터가 포함된 Excel 워크시트가 표시됩니다.

Word 문서를 추가하려면

  1. Visual C# 2010 이상 버전에서 Office 프로그래밍을 향상시키는 추가 방식을 설명하기 위해 다음 코드는 Word 응용 프로그램을 열고 Excel 워크시트에 연결되는 아이콘을 만듭니다.

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

    Add 메서드에는 참조 매개 변수 4개가 있습니다(모두 선택적 매개 변수임). Visual C# 2010 이상 버전에서는 기본값을 사용하려는 경우 모든 매개 변수 또는 원하는 매개 변수의 인수를 생략할 수 있습니다. Visual C# 2008 이하 버전에서는 각 매개 변수에 대해 인수를 제공해야 하며 매개 변수가 참조 매개 변수이므로 인수는 변수여야 합니다.

    PasteSpecial 메서드는 클립보드의 내용을 삽입합니다. 이 메서드에는 참조 매개 변수 7개가 있습니다(모두 선택적 매개 변수임). 다음 코드는 이러한 매개 변수 중 두 개에 대해 인수를 지정합니다. 그 중 하나는 클립보드 내용의 소스에 대한 링크를 만드는 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개가 있습니다(모두 선택적 매개 변수임). 명명된 인수와 선택적 인수를 사용하여 이러한 매개 변수 중 일부 또는 모두에 대해 인수를 제공할 수도 있고 모든 매개 변수에 인수를 제공하지 않을 수도 있습니다. 위의 문에서는 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# 프로그래밍 가이드)