No tags :(

Share it

This is part #2 of a series of tutorial focusing on how to generate Excel document from C# with late binding technique. Note that my WordPress theme is not code friendly, so my apologize in advance.

If you're looking for part #1:

Using The Object

In the previous article, I wrote a very basic class to create an Excel interop object. Now let's make some uses of that object.
Before we can do any spreadsheet operation, we need to create a new  worksheet. We will create four new objects in our code that will be used to wrap the workbook collection, actual workbook, active worksheet, and cells range. Here is the declaration code:

object workbooks_collection;
object workbook;
object sheet;
object range;

So we have the object declared, now we can create the COM object with these codes:

//create a new workbook collection
workbooks_collection = xls.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, xls, null);

//create a new workbook
workbook = workbooks_collection.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, workbooks_collection, null);

//create a new worksheet
sheet = workbook.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, workbook, null);

Once a new worksheet created, we can then use it for spreadsheet operation.
Now let's try to write something on cell A1. First we must set cell A1 into our range object with this code:

//assign cell A1 to range object
range = sheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, sheet, new object[] { "A1" });

And then we can assign the cell value to range object with this code:

//write something to cell A1
range.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, range, new object[] { "something" });

And that's it, our code will write "something" into cell A1.

Now we just need to integrate these codes into our class that we created on article #1. You can download the complete code here for the export_excel_class only, and here for the usage example.