Pages

Showing posts with label InterOp. Show all posts
Showing posts with label InterOp. Show all posts

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!

Monday, May 8, 2017

Dynamic C# para usar Excel sin los Assemblies de InterOp

Vamos a ver como podemos exportar a un archivo Excel desde C# usanto el Interop COM pero sin los assemblies de Interop de Excel. Puede que parezca imposible, pero C# lo hara por ;).

Para este ejemplo, primero creamos una aplicacion tipo Consola:



Ahora vamos a adicionar codigo para exportar datos a una hoja de Excel, pero tomen nota que no adicionamos ninguna referencia extra a algun dll Interop de office, ni adicionamos ningun using especial, Pero vamos a escribir el codigo como si lo hubieramos hecho.


Cuando tratamos de usar funciones especificas que sabemos estan en las librerias del Interop de excel, como el "Visible = true" vemos un error de compilacion, claramente vemos el subrayado rojo.  Esto es porque hemos declarado nuestro excel como un tipo Objeto, lo cual si es, pero no podemos indicar un 'objeto tipo excel' por que no tenemos referencia a las librerias Interop.