【问题标题】:Using late binding to get a specific instance of Excel in C#在 C# 中使用后期绑定获取特定的 Excel 实例
【发布时间】:2009-10-13 04:54:29
【问题描述】:

在后期绑定的一些帮助之后。

我正在尝试后期绑定 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);
 }

有什么想法吗?

干杯,

戴尔。

【问题讨论】:

    标签: c# excel late-binding


    【解决方案1】:

    获取一个特定 Excel 实例需要您使用AccessibleObjectFromWindow API

    这在 Andrew Whitechapel 的文章 Getting the Application Object in a Shimmed Automation Add-in 中有很好的解释。

    但是,您想要的是使用后期绑定来执行它。 divo 在这里详细描述了这一点:How to use use late binding to get excel instance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多