Pages

Tuesday, May 9, 2017

Dynamic C# to use Excel without the InterOp Assemblies

We will see how we can export to excel  using the COM Interop but without the Interop assemblies. Might seem impossible, but C# will do it.

First, lets create a console Application:



Now we will add code to export data to an Excel sheet, but notice that we will not add any extra reference or 'using' to any Interop Library, But we will write code as if we had done that.


As we try to use Excel specific calls we get a compile error, clearly we see the squiggly red line.  This is because we just declared the Excel Type as an Object, which it is, but we can't say an 'excel application object' because we don't have the Interop assemblies linked. 

Here is were we will make use of the   ...   drum roll ... Dynamic C# type.

This will allow us to compile just fine, The dynamic type will accept any type we get at run time, We just need to be careful not to make calls that would fail at run time, like a method that does not exists in the excel object we will get. 
Think of Dynamic (at least on this example ) as telling the compiler "Be cool, I have things under control, you will see it at run time". The only cost its not having the 'Intellisense' to help us when editing the code since Visual studio does not know the specific type we will get.

Now with the dynamic type we can compile just fine, no red lines. Just remember, that Excel should be registered on our machine for it to work.


In this case our excel dynamic object would be of type 'Excel.Application' but that only happens at run time. We run the program to verify.



And there you have it, Dynamic C# type just helped us simplify our code.

And that, my friend, It's all!

No comments:

Post a Comment