gpt4 book ai didi

C#向Excel工作表添加内容

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:25 25 4
gpt4 key购买 nike

如何使用 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";

并返回:

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";

最佳答案

要访问您使用的场景中的工作簿:

  Globals.ThisAddIn.Application.Workbooks...

MSDN 引用:Programming VSTO Add-Ins

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

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

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

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

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

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

关于C#向Excel工作表添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com