Tags

, , , ,


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.

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 on my website : http://amri-mlee.com/c-late-binding-excel-interop-tutorial-part-2/ (you’ll find the download link on the end of article).

Advertisements