如何从 Microsoft Visual C#.NET 自动执行 Microsoft Excel

摘要

本文演示如何使用 Microsoft Visual C# .NET 为 Microsoft Excel 创建自动化客户端。

更多信息

自动化是允许使用 Visual C# .NET 等语言编写的应用程序以编程方式控制其他应用程序的过程。 自动化到 Excel 允许你执行诸如创建新工作簿、将数据添加到工作簿或创建图表等操作。 使用 Excel 和其他 Microsoft Office 应用程序,几乎可以通过用户界面手动执行的所有操作也可以使用自动化以编程方式执行。

Excel 通过对象模型公开此编程功能。 对象模型是类和方法的集合,它们充当 Excel 逻辑组件的对应项。 例如,有一个 Application 对象、一个 Workbook 对象和一个 Worksheet 对象,其中每个对象都包含这些 Excel 部分的功能。 若要从 Visual C# .NET 访问对象模型,可以设置对类型库的项目引用。

本文演示如何设置对 Visual C# .NET 的 Excel 类型库的适当项目引用,并提供用于自动执行 Excel 的示例代码。

为 Microsoft Excel 创建自动化客户端

  1. 启动 Microsoft Visual Studio .NET。

  2. 在“文件”菜单上,单击“新建”,然后单击“项目”。 从 Visual C# 项目类型中选择 Windows 应用程序。 默认情况下会创建 Form1。

  3. 添加对 Microsoft Excel 对象库的引用。 为此,请按照下列步骤操作:

    1. 在"项目"菜单上单击"添加引用"。
    2. 在“COM”选项卡上,找到 Microsoft Excel 对象库,然后单击“选择”。

    注意 Microsoft Office 2003 包括主要互操作程序集 (PIA) 。 Microsoft Office XP 不包括 PIA,但可以下载它们。

    1. 在“添加引用”对话框中单击“确定”以接受所选内容。 如果系统提示为所选库生成包装器,请单击“是”。
  4. 在“视图”菜单上,选择“工具箱”以显示工具箱,然后将按钮添加到 Form1。

  5. 双击 Button1。 将显示窗体的代码窗口。

  6. 在代码窗口中,替换以下代码:

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

    与:

    private void button1_Click(object sender, System.EventArgs e)
    {
    Excel.Application oXL;
    Excel._Workbook oWB;
    Excel._Worksheet oSheet;
    Excel.Range oRng;
    
    try
    {
    //Start Excel and get Application object.
    oXL = new Excel.Application();
    oXL.Visible = true;
    
    //Get a new workbook.
    oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
    oSheet = (Excel._Worksheet)oWB.ActiveSheet;
    
    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";
    
    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment = 
    Excel.XlVAlign.xlVAlignCenter;
    
    // Create an array to multiple values at once.
    string[,] saNames = new string[5,2];
    
    saNames[ 0, 0] = "John";
    saNames[ 0, 1] = "Smith";
    saNames[ 1, 0] = "Tom";
    saNames[ 1, 1] = "Brown";
    saNames[ 2, 0] = "Sue";
    saNames[ 2, 1] = "Thomas";
    saNames[ 3, 0] = "Jane";
    saNames[ 3, 1] = "Jones";
    saNames[ 4, 0] = "Adam";
    saNames[ 4, 1] = "Johnson";
    
    //Fill A2:B6 with an array of values (First and Last Names).
         oSheet.get_Range("A2", "B6").Value2 = saNames;
    
    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";
    
    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";
    
    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();
    
    //Manipulate a variable number of columns for Quarterly Sales Data.
    DisplayQuarterlySales(oSheet);
    
    //Make sure Excel is visible and give the user control
    //of Microsoft Excel's lifetime.
    oXL.Visible = true;
    oXL.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" );
    }
    }
    
    private void DisplayQuarterlySales(Excel._Worksheet oWS)
    {
    Excel._Workbook oWB;
    Excel.Series oSeries;
    Excel.Range oResizeRange;
    Excel._Chart oChart;
    String sMsg;
    int iNumQtrs;
    
    //Determine how many quarters to display data for.
    for( iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
    {
    sMsg = "Enter sales data for ";
    sMsg = String.Concat( sMsg, iNumQtrs );
    sMsg = String.Concat( sMsg, " quarter(s)?");
    
    DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?", 
    MessageBoxButtons.YesNo );
    if (iRet == DialogResult.Yes)
    break;
    }
    
    sMsg = "Displaying data for ";
    sMsg = String.Concat( sMsg, iNumQtrs );
    sMsg = String.Concat( sMsg, " quarter(s)." );
    
    MessageBox.Show( sMsg, "Quarterly Sales" );
    
    //Starting at E1, fill headers for the number of columns selected.
    oResizeRange = oWS.get_Range("E1", "E1").get_Resize( Missing.Value, iNumQtrs);
    oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";
    
    //Change the Orientation and WrapText properties for the headers.
    oResizeRange.Orientation = 38;
    oResizeRange.WrapText = true;
    
    //Fill the interior color of the headers.
    oResizeRange.Interior.ColorIndex = 36;
    
    //Fill the columns with a formula and apply a number format.
    oResizeRange = oWS.get_Range("E2", "E6").get_Resize( Missing.Value, iNumQtrs);
    oResizeRange.Formula = "=RAND()*100";
    oResizeRange.NumberFormat = "$0.00";
    
    //Apply borders to the Sales data and headers.
    oResizeRange = oWS.get_Range("E1", "E6").get_Resize( Missing.Value, iNumQtrs);
    oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
    
    //Add a Totals formula for the sales data and apply a border.
    oResizeRange = oWS.get_Range("E8", "E8").get_Resize( Missing.Value, iNumQtrs);
    oResizeRange.Formula = "=SUM(E2:E6)";
    oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle 
    = Excel.XlLineStyle.xlDouble;
    oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight 
    = Excel.XlBorderWeight.xlThick;
    
    //Add a Chart for the selected data.
    oWB = (Excel._Workbook)oWS.Parent;
    oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value, 
    Missing.Value, Missing.Value );
    
    //Use the ChartWizard to create a new chart from the selected data.
    oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize( 
    Missing.Value, iNumQtrs);
    oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
    Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value, 
    Missing.Value, Missing.Value, Missing.Value, Missing.Value );
    oSeries = (Excel.Series)oChart.SeriesCollection(1);
    oSeries.XValues = oWS.get_Range("A2", "A6");
    for( int iRet = 1; iRet <= iNumQtrs; iRet++)
    {
    oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
    String seriesName;
    seriesName = "=\"Q";
    seriesName = String.Concat( seriesName, iRet );
    seriesName = String.Concat( seriesName, "\"" );
    oSeries.Name = seriesName;
    }  
    
    oChart.Location( Excel.XlChartLocation.xlLocationAsObject, oWS.Name );
    
    //Move the chart so as not to cover your data.
    oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value );
    oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
    oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value );
    oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
    }
    
    
  7. 滚动到代码窗口的顶部。 将以下行添加到 using 指令列表的末尾:

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

测试自动化客户端

  1. 按 F5 生成并运行程序。
  2. 单击窗体上的 Button1。 程序启动 Excel 并在新工作表上填充数据。
  3. 当系统提示输入季度销售数据时,请单击“是”。 链接到季度数据的图表将添加到工作表。

参考

有关详细信息,请参阅 Microsoft 开发人员网络 (MSDN) 网站