使用c#写入excel单元格

发布于 2024-12-11 22:21:25 字数 220 浏览 5 评论 0原文

我创建了一个 Visual Studio Excel 工作簿项目,其中包含 ThisWorkbook 类,然后包含一个函数类,以便我可以创建自己的 Excel 函数。我正在尝试通过使用该函数使用 C# 将值写入单元格。我可以通过函数类写入 Excel 单元格,但只能通过创建新的应用程序/工作簿。所以每次我使用这个Excel函数时,它都会打开一个新的Excel实例。有没有办法可以写入当前 Excel 工作簿中已打开的单元格?

I created a visual studio excel workbook project which contains ThisWorkbook class and I then included a functions class so that I can create my own excel function. I am trying to write a value to a cell using c# through the use of the function. I can write to the excel cell through the function class but only by creating a new application/workbook. So everytime I use this excel function, it will open new instance of excel. Is there a way I can write to a cell in the current excel workbook that is already opened?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜味拾荒者 2024-12-18 22:21:25

看,我尝试过,这段代码有效:

private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
    Excel.Worksheet ws = (Excel.Worksheet)(sender as Workbook).ActiveSheet;

    System.Random rnd = new System.Random();

    for (int i = 1; i <= 20; i++)
        ws.Cells[i, 2] = rnd.Next(100);
}

所以如您所见,您可以访问工作表并使用 ws.Cells 来操作单元格值。

这里有很多示例:

了解 Excel 对象.NET 开发人员视角的模型

Look, I tried and this code works:

private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
    Excel.Worksheet ws = (Excel.Worksheet)(sender as Workbook).ActiveSheet;

    System.Random rnd = new System.Random();

    for (int i = 1; i <= 20; i++)
        ws.Cells[i, 2] = rnd.Next(100);
}

so as you see you can access the Worksheet and use ws.Cells to manipulate cell values.

there are plenty of examples here:

Understanding the Excel Object Model from a .NET Developer's Perspective

带刺的爱情 2024-12-18 22:21:25

您可能会创建一个新的 Excel 应用程序,而不是连接到活动的 Excel 应用程序。

使用 GetActiveObject 获取参考到 Excel 应用程序对象。

You probably create a new Excel application, instead of connecting to the active Excel application.

Use the GetActiveObject to get your reference to the Excel application object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文