Loading all COM types of Excel dynamically?

2019-05-12 05:39发布

I want to explore this path of working with Excel dynamically.


I want to use Excel in my C# application without including dlls and stuff. I would just check first if the required Excel version is installed and run it.

First I want to get all the types I need but I can't get hold of them:

// works
Type typeExcel = Type.GetTypeFromProgID("Excel.Application");
object excel = Activator.CreateInstance(typeExcel);
object workbooks = typeExcel.InvokeMember("Workbooks", BindingFlags.GetProperty, null, excel, null);

// this doesn't work, returns null
Type typeWorkbooks = Type.GetTypeFromProgID("Excel.Workbooks");

Without the correct types I can't invoke members. So what am I doing wrong ? How do I load all types I need and know that they are there ? My current Excel version is 2003.


Reasons for this: If I include COM Libraries that are not installed on the target system my application wont start. If I load them dynamically I can check for their existence and notify the user about missing functionality.

2条回答
闹够了就滚
2楼-- · 2019-05-12 06:17

Use dynamic.

Type typeExcel = Type.GetTypeFromProgID("Excel.Application");

dynamic excel = Activator.CreateInstance(typeExcel);
excel.Visible = true;

dynamic workbooks = excel.Workbooks;
workbooks.Add();
workbooks.Add();

Also see this answer.

查看更多
成全新的幸福
3楼-- · 2019-05-12 06:32

If I include COM Libraries that are not installed on the target system my application wont start.

The cure you are looking for is considerably worse than the problem. There isn't anything that pretty about late-binding Office code as you are attempting in your snippet. The dynamic keyword supported in C# version 4 certainly makes the syntax a lot friendlier. There's however nothing friendly about it at code-writing time, you won't get any IntelliSense. And nothing friendly at run-time, the mistakes you make at coding-time will cause exceptions and late-binding has considerable overhead.

There are simple counter-measures to ensure the interop assemblies are available:

  • Ask your user to install the Office Primary Interop Assemblies (PIAs).

  • It is quite rare to actually need a PIA, it is only necessary when you expose an Office type in your own public methods and use it in another assembly. Select the Microsoft.Office.Interop assemblies in your Reference node and set their Copy Local property to true. Rebuild and you'll get those assemblies in your build directory. Copy them along with your own executables to the client machine.

  • VS2010 and up have the Golden Solution to this deployment detail. Select the interop assembly in your Reference node and set the Embed Interop Types property to True. The interop declarations will now be merged into your own executable and you don't have to deploy the interop assemblies or PIA anymore.

Since you accepted the dynamic solution, available on VS2010 and up, the last bullet is the one you want.

查看更多
登录 后发表回答