下面的代码示例演示如何使用 COM interop 创建 Excel 电子表格。有关 Excel 的更多信息,请参见“Microsoft Excel Objects”(Microsoft Excel 对象)“Open Method”(Open 方法)

此示例演示如何在 C# 中使用 .NET Framework COM interop 功能打开现有的 Excel 电子表格。使用 Excel 程序集来打开 Excel 电子表格中一定范围内的单元格并向其中输入数据。

Note注意

为使此代码正常运行,必须在系统中安装 Excel

Note注意

显示的对话框和菜单命令可能会与“帮助”中描述的不同,具体取决于您现用的设置或版本。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见 Visual Studio 设置

使用 COM interop 创建 Excel 电子表格

  1. 在 Visual Studio 中创建新的 C# 控制台应用程序,将其命名为 CreateExcelWorksheet

  2. 将 Excel 程序集作为引用添加到项目中:右键单击项目,选择“添加引用”。

  3. 单击“添加引用”对话框的“COM”选项卡,找到“Microsoft Excel 11 对象库”。

  4. 双击“Microsoft Excel 11 对象库”,然后按“确定”。

    Note注意

    根据安装的 Office 版本的不同,Excel 程序集可能名为“Excel 10 对象库”或“Excel 11 对象库”。

  5. 复制下面的代码并将其粘贴到 Program.cs 文件中覆盖原有内容。

    C# CopyCode image复制代码
    using System;
    using System.Reflection; 
    using Microsoft.Office.Interop.Excel;
    
    public class CreateExcelWorksheet
    {
        static void Main()
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    
            if (xlApp == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                return;
            }
            xlApp.Visible = true;
    
            Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = (Worksheet)wb.Worksheets[1];
    
            if (ws == null)
            {
                Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
            }
    
            // Select the Excel cells, in the range c1 to c7 in the worksheet.
            Range aRange = ws.get_Range("C1", "C7");
    
            if (aRange == null)
            {
                Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs.");
            }
    
            // Fill the cells in the C1 to C7 range of the worksheet with the number 6.
            Object[] args = new Object[1];
            args[0] = 6;
            aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);
        
            // Change the cells in the C1 to C7 range of the worksheet to the number 8.
            aRange.Value2 = 8;
        }
    }
    

安全

若要使用 COM interop,您必须拥有“管理员”或“超级用户”安全权限。有关安全的更多信息,请参见“.NET Framework Security”(.NET Framework 安全性)

请参见

任务

如何:使用 COM Interop 进行 Word 拼写检查(C# 编程指南)

概念

C# 编程指南
互操作性概述(C# 编程指南)

其他资源

.NET Compact Framework 中的互操作性
COM 互操作性示例