추가 정보
한 번에 하나씩 셀을 채우지 않고 여러 셀 범위를 채우려면 Range 개체의 Value 속성을 2차원 배열로 설정하면 됩니다. 마찬가지로 Value 속성을 사용하여 한 번에 여러 셀에 대한 2차원 배열 값을 가져올 수 있습니다. 다음 단계에서는 2차원 배열을 사용하여 데이터를 설정하고 검색하는 과정을 보여 줍니다.
Microsoft Excel용 자동화 클라이언트 빌드

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

2. 파일 메뉴에서 새로 만들기를 누르고 프로젝트를 누릅니다. Visual C# 프로젝트 형식에서 Windows 응용 프로그램을 선택합니다. 기본적으로 Form1이 만들어집니다.

3. Visual Studio 2005의 경우 Microsoft Excel 11.0 Object Library에 대한 참조나, Visual Studio .NET의 경우 Microsoft Excel Object Library에 대한 참조를 추가합니다. 해당 참조를 추가하려면 다음과 같이 하십시오.

a.  프로젝트 메뉴에서 참조 추가를 누릅니다.
b.  COM 탭에서 Microsoft Excel Object Library를 찾아 선택을 누릅니다.

Visual Studio 2005의 경우 COM 탭에서 Microsoft Excel 11.0 Object Library를 찾습니다.

참고 Microsoft Office 2003에는 PIA(기본 Interop 어셈블리)가 포함되어 있습니다. Microsoft Office XP에는 PIA가 포함되어 있지 않지만 PIA를 다운로드할 수 있습니다. Office XP PIA에 대한 자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
328912 (http://support.microsoft.com/kb/328912/) Microsoft Office XP PIA를 다운로드할 수 있다 
c.  참조 추가 대화 상자에서 확인을 눌러 선택한 내용을 적용합니다. 선택한 라이브러리에 대해 래퍼를 생성할 것인지 묻는 메시지가 나타나면 예를 누릅니다.

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

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

6. Button1을 두 번 누릅니다. 해당 폼에 대한 코드 창이 나타납니다.

7. 코드 창에서


private void button1_Click(object sender, System.EventArgs e)
{
}
   
위의 코드를 아래와 같이 바꿉니다.      

//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에 작성합니다. Windows Forms 디자이너에서는 사용자가 도구 상자에서 컨트롤을 끌어 놓는 방법으로 수행한 모든 작업을 구현하는 코드를 Form1.designer.cs 파일에 작성합니다. Visual C# 2005의 Windows Forms 디자이너에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하십시오.
http://msdn2.microsoft.com/ko-kr/library/ms173077.aspx (http://msdn2.microsoft.com/ko-kr/library/ms173077.aspx)

8. Form1의 디자인 보기로 돌아가서 Button2를 두 번 누릅니다.

9. 코드 창에서

private void button2_Click(object sender, System.EventArgs e)
{
}
   
위의 코드를 아래와 같이 바꿉니다.

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" );

}

}


10. 코드 창의 맨 위로 스크롤합니다. using 지시문 목록의 끝에 다음 행을 추가합니다.

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

자동화 클라이언트 테스트
1. F5 키를 눌러 예제 프로그램을 빌드하고 실행합니다.

2. Button1을 누릅니다. Microsoft Excel이 시작되어 새로운 통합 문서가 나타나고 첫 번째 워크시트의 A1:E5 셀이 배열의 숫자 데이터로 채워집니다.

3. Button2를 누릅니다. A1:E5 셀의 데이터가 새로운 배열에 삽입되고 결과가 메시지 상자에 표시됩니다.

4. FillWithStrings를 선택하고 Button1을 눌러 A1:E5 셀을 문자열 데이터로 채웁니다.

+ Recent posts