如何通过Visual C#使Excel自动执行操作以使用数组来填充或获取某区域中的数据
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。