Visual C#을 사용하여 배열을 사용하여 범위에서 데이터를 채우거나 가져오는 방법으로 Excel을 자동화하는 방법

요약

이 문서에서는 Microsoft Visual C# 2005 또는 Microsoft Visual C# .NET을 사용하여 배열을 사용하여 다중 셀 범위의 값을 채우고 검색하여 Microsoft Excel을 자동화하는 방법을 보여 줍니다.

추가 정보

셀을 한 번에 하나씩 채우지 않고 다중 셀 범위를 채우려면 Range 개체의 Value 속성을 2차원 배열로 설정할 수 있습니다. 마찬가지로 Value 속성을 사용하여 여러 셀에 대한 2차원 값 배열을 한 번에 검색할 수 있습니다. 다음 단계에서는 2차원 배열을 사용하여 데이터를 설정하고 검색하는 프로세스를 보여 줍니다.

Microsoft Excel용 Automation 클라이언트 빌드

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

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

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

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

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

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

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

  5. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시합니다. Form1에 단추 2개와 확인란을 추가합니다.

  6. 확인란의 이름 및 텍스트 속성을 FillWithStrings로 설정합니다.

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

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

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

    with:

       //Declare these two variables globally so you can access them from both
       //Button1 and Button2.
       Excel.Application objApp;
       Excel._Workbook objBook;
    
    private void button1_Click(object sender, System.EventArgs e)
       {
          Excel.Workbooks objBooks;
          Excel.Sheets objSheets;
          Excel._Worksheet objSheet;
          Excel.Range range;
    
    try
          {
             // Instantiate Excel and start a new workbook.
             objApp = new Excel.Application();
             objBooks = objApp.Workbooks;
             objBook = objBooks.Add( Missing.Value );
             objSheets = objBook.Worksheets;
             objSheet = (Excel._Worksheet)objSheets.get_Item(1);
    
    //Get the range where the starting cell has the address
             //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
             range = objSheet.get_Range("A1", Missing.Value);
             range = range.get_Resize(5, 5);
    
    if (this.FillWithStrings.Checked == false)
             {
                //Create an array.
                double[,] saRet = new double[5, 5];
    
    //Fill the array.
                for (long iRow = 0; iRow < 5; iRow++)
                {
                   for (long iCol = 0; iCol < 5; iCol++)
                   {
                      //Put a counter in the cell.
                      saRet[iRow, iCol] = iRow * iCol;
                   }
                }
    
    //Set the range value to the array.
                range.set_Value(Missing.Value, saRet );
             }
    
    else
             {
                //Create an array.
                string[,] saRet = new string[5, 5];
    
    //Fill the array.
                for (long iRow = 0; iRow < 5; iRow++)
                {
                   for (long iCol = 0; iCol < 5; iCol++)
                   {
                      //Put the row and column address in the cell.
                      saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString();
                   }
                }
    
    //Set the range value to the array.
                range.set_Value(Missing.Value, saRet );
             }
    
    //Return control of Excel to the user.
             objApp.Visible = true;
             objApp.UserControl = true;
          }
          catch( Exception theException ) 
          {
             String errorMessage;
             errorMessage = "Error: ";
             errorMessage = String.Concat( errorMessage, theException.Message );
             errorMessage = String.Concat( errorMessage, " Line: " );
             errorMessage = String.Concat( errorMessage, theException.Source );
    
    MessageBox.Show( errorMessage, "Error" );
          }
       }
    

    참고 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 Designer에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요.

    프로젝트 만들기(Visual C#)

  9. Form1의 디자인 보기로 돌아가서 Button2를 두 번 클릭합니다.

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

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

with:

private void button2_Click(object sender, System.EventArgs e)
   {
      Excel.Sheets objSheets;
      Excel._Worksheet objSheet;
      Excel.Range range;

try
      {
         try
         {
            //Get a reference to the first sheet of the workbook.
            objSheets = objBook.Worksheets;
            objSheet = (Excel._Worksheet)objSheets.get_Item(1);
         }

catch( Exception theException ) 
         {
            String errorMessage;
            errorMessage = "Can't find the Excel workbook.  Try clicking Button1 " +
               "to create an Excel workbook with data before running Button2.";

MessageBox.Show( errorMessage, "Missing Workbook?");

//You can't automate Excel if you can't find the data you created, so 
            //leave the subroutine.
            return;
         }

//Get a range of data.
         range = objSheet.get_Range("A1", "E5");

//Retrieve the data from the range.
         Object[,] saRet;
         saRet = (System.Object[,])range.get_Value( Missing.Value );

//Determine the dimensions of the array.
         long iRows;
         long iCols;
         iRows = saRet.GetUpperBound(0);
         iCols = saRet.GetUpperBound(1);

//Build a string that contains the data of the array.
         String valueString;
         valueString = "Array Data\n";

for (long rowCounter = 1; rowCounter <= iRows; rowCounter++)
         {
            for (long colCounter = 1; colCounter <= iCols; colCounter++)
            {

//Write the next value into the string.
               valueString = String.Concat(valueString,
                  saRet[rowCounter, colCounter].ToString() + ", ");
            }

//Write in a new line.
            valueString = String.Concat(valueString, "\n");
         }

//Report the value of the array.
         MessageBox.Show(valueString, "Array Values");
      }

catch( Exception theException ) 
      {
         String errorMessage;
         errorMessage = "Error: ";
         errorMessage = String.Concat( errorMessage, theException.Message );
         errorMessage = String.Concat( errorMessage, " Line: " );
         errorMessage = String.Concat( errorMessage, theException.Source );

MessageBox.Show( errorMessage, "Error" );
      }
   }
  1. 코드 창의 맨 위로 스크롤합니다. using 지시문 목록의 끝에 다음 줄을 추가합니다.

    using System.Reflection; 
    using Excel =  Microsoft.Office.Interop.Excel;
    

Automation 클라이언트 테스트

  1. F5 키를 눌러 샘플 프로그램을 빌드하고 실행합니다.
  2. Button1을 클릭합니다. 이 프로그램은 새 통합 문서로 Microsoft Excel을 시작하고 첫 번째 워크시트의 A1:E5 셀을 배열의 숫자 데이터로 채웁니다.
  3. Button2를 클릭합니다. 프로그램은 셀 A1:E5의 데이터를 새 배열로 검색하고 메시지 상자에 결과를 표시합니다.
  4. FillWithStrings를 선택한 다음 Button1을 클릭하여 셀 A1:E5를 문자열 데이터로 채웁니다.

참조

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

Visual Studio를 사용한 Microsoft Office 개발