使用后期绑定在C#中获取特定的Excel实例

只是在后期绑定的一点帮助。

我想延迟绑定excel,我没有任何问题做到这一点。 只有当我遇到一个以上的excel实例时,我遇到了一些问题。

我想能够确定什么样的Excel绑定到(和链接事件等)。 主要原因是我有一个应用程序,从第三方工具打开Excel文件,事件不处理。 我希望能够利用我所知道的开发事件的excel实例。 唯一的问题是如果excel已经被用户打开(无所谓)。

如果在绑定后打开excel,显然我不会遇到问题。 只有当excel已经打开。

这似乎是绑定到第一个开放的例程。

这里是实际的代码:

Type excelType = Type.GetTypeFromProgID("Excel.Application"); // Throw exception if the type wasn't found if (excelType == null) throw new Exception(error); //Get the Excel.Application Type by creating a new type instance excelApplication = Marshal.GetActiveObject("Excel.Application"); //Throw exception if the object couldn't be created if (excelApplication == null) throw new Exception(error); this.withEvents = withEvents; //Create link between the Word.Applications events and the ApplicationEvents2_WordEvents class if (this.withEvents) { excelEvents = new ExcelApplicationEvents(); //holds the connection point references of the Word.Application object IConnectionPointContainer connectionPointContainer = excelApplication as IConnectionPointContainer; //Find the connection point of the GUID found from Red Gate's .Net Reflector Guid guid = new Guid("00024413-0000-0000-C000-000000000046"); connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint); //Advise the Word.Application to send events to the event handler connectionPoint.Advise(excelEvents, out sinkCookie); excelEvents.WorkbookBeforeSaveEvent += new EventHandler<WorkbookEventArgs>(ExcelEventsWorkbookBeforeSaveEvent); } 

有任何想法吗?

干杯,

戴尔。

获取Excel的特定实例需要使用AccessibleObjectFromWindow API 。

在 Andrew Whitechapel 的“Shimmed Automation Add-in”中的文章“ 获取应用程序对象”中对此进行了很好的解释。

然而,你想要的是使用后期绑定来执行它。 这在这里由divo详细描述: 如何使用后期绑定来获得excel实例 。