C# 添加内容到 Excel 工作表

C# add content to Excel Worksheet

如何使用 C# 向活动工作簿的 Excel 单元格添加值?我是 VSTO C# 的新手,找不到适合我的解决方案...

这是我的代码(来自这个问题Write to cell in excel using c#):

using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelSDRAddIn
{
    public partial class UserControlSDR : UserControl
    {
        public UserControlSDR()
        {
            InitializeComponent();
        }

        private void btnTemplate_Click(object sender, EventArgs e)
        {
            Excel.Worksheet ws = (Excel.Worksheet)(sender as Workbook).ActiveSheet;
            ws.Cells[1, 1] = "Value";
        }
    }
}

在 运行 之后,我在这一行 Excel.Worksheet ws = (Excel.Worksheet)(sender as Workbook).ActiveSheet;:

得到以下异常

An exception of type 'System.NullReferenceException' occurred in ExcelSDRAddIn.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

也试过这个:

    dynamic excelType = Type.GetTypeFromProgID("Excel.Application");
    excelType.Visible = true;
    excelType.Workbooks.Add();
    dynamic workSheet = excelType.ActiveSheet;

    workSheet.Cells[1, 1] = "Names";
    workSheet.Cells[1, 2] = "Age";

和returns:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: 'System.Reflection.TypeInfo' does not contain a definition for 'Visible'

另一个失败的例子:

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
...
var Excel = new Excel.Application();
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.ActiveWorkbook;
oSheet = oWB.ActiveSheet;
oSheet.Cells[1, 1] = "Value";

根据您的方法名称 btnTemplate_Click 我敢打赌您正在使用按钮来调用此函数。所以在这种情况下,发件人是 Button 而不是 Workbook。当您尝试将发件人拆箱为 Workbook 时,您将得到 null 并且在尝试访问 ActiveSheet 属性.

时得到 NullReferenceException

请再读一遍链接参考中的问题。它指出:

I created a visual studio excel workbook project which contains ThisWorkbook class

我不确定 class 是什么样子,但我认为这是方法 private void ThisWorkbook_Startup(object sender, System.EventArgs e) 应该挂接到某种“启动事件”的地方。

要访问您使用的方案中的工作簿:

  Globals.ThisAddIn.Application.Workbooks...

MSDN 参考:Programming VSTO Add-Ins

以下代码示例演示如何使用“应用程序”字段在 Microsoft Office 的 VSTO 外接程序中创建新工作簿 Excel。此示例旨在从 ThisAddIn class.

运行
  Excel.Workbook newWorkbook = this.Application.Workbooks.Add(System.Type.Missing);  

要从 ThisAddIn class 外部执行相同的操作,请使用 Globals 对象访问 ThisAddIn class。有关全局对象的详细信息,请参阅对 Office 项目中对象的全局访问。

  Excel.Workbook newWorkbook = Globals.ThisAddIn.Application.Workbooks.Add(System.Type.Missing);  

编辑:您需要使用此代码来获取活动工作表

  Excel.Worksheet ws = (Excel.Worksheet)Globals.ThisAddin.Application.ActiveSheet;