C#Excel如何使用已经打开的工作簿
这个问题是从我最后一个问题的学习中提出的:上一个问题
我需要能够将文本发送到已打开的选定工作表。
我认为这很接近,但它没有起作用:
string wb = cmb_BookName.Text.ToString();
string ws = cmb_SheetName.Text.ToString();
if (chkContainer.Checked)
{
Excel.Application oexcel = new Excel.Application();
Excel.Workbook wkbk = (Excel.Workbook)oexcel.Workbooks[wb];
Excel.Worksheet wksk = (Excel.Worksheet)wkbk.Sheets[ws];
Range cellRange = wksk.Range["D48:D48"];
cellRange.Value = cboContainer.Text;
}
该代码没有错误构建,但是当运行时,该代码会停在线上试图获取工作簿,请参阅图像。
所以基本上我的问题仍然是如何我是否可以使用已经打开的Excel工作簿?
似乎我发现的大多数文章都在打开一个Excel文件,然后使用它。就我而言,我需要使用已经打开的Excel工作簿。
This is a question that was taken from the learning's of my last question: Previous Question
I need to be able to send text to a selected worksheet that is already opened.
This, I think is close but it didn't work:
string wb = cmb_BookName.Text.ToString();
string ws = cmb_SheetName.Text.ToString();
if (chkContainer.Checked)
{
Excel.Application oexcel = new Excel.Application();
Excel.Workbook wkbk = (Excel.Workbook)oexcel.Workbooks[wb];
Excel.Worksheet wksk = (Excel.Worksheet)wkbk.Sheets[ws];
Range cellRange = wksk.Range["D48:D48"];
cellRange.Value = cboContainer.Text;
}
The code builds without errors but when running it stops at the line trying to get the workbook, see image.
So basically my question still is how do I work with an excel workbook that is already opened?
Seems like most of the articles that I find are opening an excel file and then working with it. In my case, I need to work with an already opened excel workbook.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
There are some helpful answers (some of them, not the accepted answer) to this question here:
但这是我的摘要答案。
尝试一下:
首先
您必须访问当前正在运行的应用程序(如果已经有多个Excel运行的实例,这可能每次都无法正常工作)
second
通过路径获取所需的工作簿(必须是Windows样式,即“ C:\ Desktop \ Myworkbook.xlsx”)
There are some helpful answers (some of them, not the accepted answer) to this question here: Accessing an open Excel Workbook in C#
But here is my summarized answer.
Try this:
First
You must access the currently running application (if there are multiple instances of Excel running already, this might not work everytime)
Second
Get the desired workbook by path, (must be windows style, i.e. "C:\Desktop\myWorkbook.xlsx")
它看起来像
元帅。getActiveObject
在基于.net Core的.NET版本中消失了。但是我在另一个论坛上找到了一个简单的解决方案。
可以像这样使用:
It looks like
Marshal.GetActiveObject
is gone in newer .NET Core based .NET versions.But I found a simple solution on another forum.
This can be used like so: