摘要
本文示範如何使用 Microsoft Visual C# 2005 或 Microsoft Visual C# .NET 將 Microsoft Excel 自動化,以使用陣列填入和擷取多儲存格範圍中的值。
其他相關資訊
若要填入多儲存格範圍而不一次填入一個儲存格,您可以將 Range 物件的 Value 屬性設定為二維陣列。 同樣地,您可以使用 Value 屬性,一次擷取多個儲存格的二維值陣列。 下列步驟示範使用二維陣列設定和擷取資料的這個程式。
建置適用于 Microsoft Excel 的自動化用戶端
啟動 Microsoft Visual Studio 2005 或 Microsoft Visual Studio .NET。
在 [檔案] 功能表上,按一下 [新增],然後按一下 [專案]。 從 Visual C# 專案類型中選取 [Windows 應用程式]。 根據預設,會建立 Form1。
在 Visual Studio 2005 中新增 Microsoft Excel 11.0 物件程式庫 的參考,或在 Visual Studio .NET 中新增 Microsoft Excel 物件程式庫的參考。 如果要執行這項操作,請依照下列步驟執行:
- 按一下 [專案] 功能表上的 [加入參考]。
- 在 [COM] 索引標籤上,找出 [Microsoft Excel 物件程式庫],然後按一下 [選取]。
在 Visual Studio 2005 中,于[COM] 索引標籤上找出[Microsoft Excel 11.0 物件庫]。
注意 Microsoft Office 2003 包含主要 Interop 元件 (PIA) 。 Microsoft Office XP 不包含 PIA,但可能會下載。
按一下 [新增參考] 對話方塊中的 [確定] 以接受您的選擇。 如果系統提示您為選取的程式庫產生包裝函式,請按一下 [是]。
在 [檢視] 功能表上,選取 [工具箱] 以顯示 [工具箱]。 將兩個按鈕和一個核取方塊新增至 Form1。
將核取方塊的 [名稱] 和 [文字] 屬性設定為 FillWithStrings。
按兩下 Button1。 表單的程式碼視窗隨即出現。
在程式碼視窗中,取代下列程式碼:
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 中變更程式碼。 根據預設,當您建立Windows Forms專案時,Visual C# 會將一個表單新增至專案。 表單名為 Form1。 代表表單的兩個檔案名為 Form1.cs 和 Form1.designer.cs。 您可以在 Form1.cs 中撰寫程式碼。 Form1.designer.cs 檔案是 Windows Forms Designer 撰寫程式碼的位置,該程式碼會實作您從 [工具箱] 拖放控制項所執行的所有動作。
如需 Visual C# 2005 中Windows Forms設計工具的詳細資訊,請造訪下列 Microsoft Developer Network (MSDN) 網站:
返回 Form1 的設計檢視,然後按兩下 Button2。
在程式碼視窗中,取代下列程式碼:
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" );
}
}
捲動至程式碼視窗的頂端。 將下列這一行新增至 using 指示詞清單的結尾:
using System.Reflection; using Excel = Microsoft.Office.Interop.Excel;
測試自動化用戶端
- 按 F5 建置 並執行範例程式。
- 按一下 [按鈕1]。 此程式會以新的活頁簿啟動 Microsoft Excel,並以陣列中的數值資料填入第一張工作表的 A1:E5 儲存格。
- 按一下 [按鈕2]。 程式會將儲存格 A1:E5 中的資料擷取到新的陣列,並在訊息方塊中顯示結果。
- 選取 [FillWithStrings],然後按一下 [Button1] 以字串資料填入儲存格 A1:E5。
參考
如需詳細資訊,請造訪下列 Microsoft Developer Network (MSDN) 網站: