这是因为最初,像Excel这样的Office应用程序的自动化只能在宏中使用VB脚本完成,并且编写这些宏的人自然倾向于转向VB.NET,或者有没有理由不将C#用于Office Automation?
好像我可以用C#实例化Excel类,就像我从VB.NET使用CreateObject一样.
excel = Type.GetTypeFromProgID("Excel.Application");
如果您必须使用Excel Automation编写.NET程序,您会使用哪种语言,除了可能有VB.NET示例之外,还有什么理由可以避免使用C#吗?
编辑:
我正在考虑编写代码,明确引用Microsoft Excel对象库和显式实例化Excel类Application对象,然后,在程序基本测试之后,修改代码以使用后期绑定以允许应用程序运行不同版本的Excel.
代码会完全不同吗?
例如,使用早期绑定我可以这样做……
var excel2 = new Microsoft.Office.Interop.Excel.Application(); excel2.Visible = true;
在迟到的时候,我会被迫使用完全不同的代码吗?
excel = Type.GetTypeFromProgID("Excel.Application"); excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);虽然有更多可用于VB.NET的代码示例,但我已经成功使用了它们.
我可以立即想到的一个区别是API方法似乎包含了可选方法参数的gajillions,这些参数在C#< 4,所以你会发现自己做的事情如下:
object missing = Type.Missing; Excel.Application xl = new Excel.Application(); xl.Workbooks.Open(fileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, missing, missing, missing, missing, missing, missing, missing);
而不仅仅是在VB.NET中:
Dim xl As New Excel.Application() xl.Workbooks.Open(fileName, 0, True, 5, "", "", true, Excel.XlPlatform.xlWindows)
VB.NET提供的一些语法糖与编写使用OLE自动化库或互操作程序集的应用程序的简洁性有很大关系.
编辑:至于早期和晚期绑定,我不能说我有任何后期绑定的经验. This article讨论了为多个版本的office应用程序安全地实现后期绑定的方法.
报价from the article:
…you can start developing your add-in using interops for the highest version of the Office application. When this is done, you can replace early-binding calls to the features introduced in this Office version with late binding calls and make sure these calls work. Then you can replace the interop assemblies referenced by your project with the interop for a previous version of the application and reiterate the procedure. Kind of refactoring. Whether this approach is useful or not, this is you who decides