本文介绍了C#创建Excel工作表后期绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Winforms,C#FW4.5打开一个后期绑定的excel工作表,如下所示:

Using winforms, C# FW4.5 to open an excel sheet with late bound, like this:

objExcel = CreateObject("Excel.Application")

现在我想使用InvokeMember方法,但是我不知道我可以调用的所有excel成员.例如,我知道我可以这样称呼它:InvokeMember("Close",...以关闭excel,但是在哪里可以找到我可以调用的所有成员以及每个成员的作用的列表?

Now I want to use the InvokeMember method, but I don't know all the members of excel I can invoke.For example, I know I can call it like this: InvokeMember("Close",... in order to close excel, but where can I find list of all the members I can invoke and what each one of them does?

推荐答案

后期约束

如果必须使用后期绑定,则使用c#4.0的dynamic关键字比InvokeMember容易得多,尽管它不会告诉您可以提前调用哪些方法.

If you must use late-binding, using c# 4.0's dynamic keyword is a whole lot easier than InvokeMember, though it won't show you what methods you can invoke ahead of time.

查看以下通过dynamic关键字使用后期绑定的代码.请注意,Visual Studio如何允许我键入任何旧内容.尽管无法提供最终成员的自动完成功能,但它确实显示了我已经使用过的商品的成员.我要等到运行时才知道它是否正确(这是后期绑定这种方式的局限性).

Check out the following code that uses late-binding via the dynamic keyword. Notice how Visual Studio allows me to type in any old thing. Though auto-complete for the final members aren't available, it does show members for items I've used already. I won't know until runtime whether I got it right (such is the limitation of late-binding this way).

...更具体地说:

早起

OP:

尽管后期绑定很好,即使使用dynamic,我也喜欢早期绑定.要获取方法列表,可以通过向您的项目中添加 Microsoft.Office.Interop.Excel 来使用早期绑定更加容易且类型安全.

Though late binding is fine, even with dynamic, I like early binding. To get a list of methods, it's much easier and type-safe to use early binding via adding Microsoft.Office.Interop.Excel to your project.

早期绑定:

var application = new Microsoft.Office.Interop.Excel.Application();
application.Visible = true;
application.ShowWindowsInTaskbar = true;

在VS中:

c#4带有一些您只在处理COM时才会看到的东西,例如索引属性-在c#类型中是不可能的.

c# 4 brings with it some stuff you'll only see when dealing with COM, like indexed properties - something not possible in c# types.

仅当针对COM interop API编写代码时,才支持C#4.0中的某些较小的语言功能

Some smaller language features in C# 4.0 are supported only when writing code against a COM interop API

例如

ws.Range["A1", "B3"].Value = 123;

...比c#4之前的版本容易得多:

...is a whole lot easier than pre-c# 4:

ws.get_Range("A1", "B3").Value2 = 123;

告诉我更多

  • C#4.0-.NET Framework 4中的新C#功能 ,MSDN Mag,2010年7月

    Tell me more

    • C# 4.0 - New C# Features in the .NET Framework 4, MSDN Mag July 2010

      动态.NET-了解动态关键字C#4 ,MSDN Mag,2011年2月

      Dynamic .NET - Understanding the Dynamic Keyword in C# 4, MSDN Mag Feb 2011

      这篇关于C#创建Excel工作表后期绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 23:35