简体   繁体   English

是否可以将Excel应用程序对象设置为指向已经打开的Excel实例?

[英]Can I set a Excel Application Object to point to an already open instance of Excel?

I am currently trying to create an export tool to push data into Excel. 我目前正在尝试创建导出工具以将数据推入Excel。 However after the first push, Excel is left open, and sometimes a user may want to leave Excel open while they push more data to another page in the same excel sheet. 但是,在第一次推送后,Excel保持打开状态,有时用户可能希望在将更多数据推送到同一excel工作表中的另一个页面时保持Excel处于打开状态。 I usually just release the COM objects once the export is done. 一旦导出完成,我通常只释放COM对象。 The way my methods work right now involves opening a new instance of excel every time I export... 我的方法现在的工作方式包括每次导出时都打开一个新的excel实例...

would it be beneficial to create a global instance of the application to use continuiously from the point I begin exporting until the point of the Excel application being closed? 创建一个应用程序的全局实例以从我开始导出到Excel应用程序关闭之间连续使用是否有益?

Should I be using event handlers to detect when Excel has been closed so I know when to release the COM objects? 我应该使用事件处理程序来检测Excel何时关闭,以便知道何时释放COM对象吗?

If I do try to make a global instance of an Excel Application, I can instantiate it and wait to release it, that way I don't need to try and find open instances of excel again.. but if I needed to find, and assign to a variable, an open instance of Excel (that has previously existed in code but had the COM objects released), how would I do this? 如果确实尝试创建Excel应用程序的全局实例,则可以实例化它,然后等待释放它,这样就无需再次尝试找到excel的打开实例..但是,如果我需要查找和将变量分配给一个Excel的开放实例(该实例先前已存在于代码中,但已释放COM对象),我该怎么做?

I have used this in the past. 我过去曾经使用过。 tPath is the path to my excel file that should be opened/reused. tPath是我的excel文件应该打开/重用的路径。

Dim exApp As New Excel.Application

'finds the workbook.  If it is already open, then it uses that.  Otherwise, it opens in new instance
Dim wb As Excel.Workbook
wb = System.Runtime.InteropServices.Marshal.BindToMoniker(tPath)
exApp = wb.Parent

You can use the Interop Library to point to the open excel-app 您可以使用Interop库指向打开的excel-app

(This code is written in C# so there could be some minor change for VB.Net) (此代码是用C#编写的,因此VB.Net可能会有一些小的更改)

oExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM