Excel via .Net 2.0 - Part 1
Having done a lot of work previously which involved automating Excel [2003] via VBA (from Access specifically - it's a fantastic way to produce reports that are easy to amend / modify / create graphs from, rather than the standard Access reporting engine) I've begun investigating the feasibility of doing the same through VB.NET.
First, you need to make sure you have the Primary Interop Assemblies installed. There's a well written reference available from msdn which does all this. Whilst it's targeted at .Net 2002/2003, it is fairly easy to map the changes to the VS 2005/.net 2.0 way of doing things, which is no doubt documented elsewhere much more clearly than I could ever manage!
Objective
Open an instance of Excel and write "Hello, world" (in Verdana) in the first cell of the first sheet
1 - Create a new VB.Net application and add a reference to the Excel PIA (as described in the MSDN article)
2 - In the code for the default form, add Imports Microsoft.Office.Interop to the top of the file.
3 - Add a button to the form and add the following to the event handler:
Dim oExcel as New Excel.Application()
Dim oBook as Excel.Workbook = oExcel.Workbooks.Add()
Dim oSheet as Excel.Worksheet = CType(oBook.Sheets.Item(1), Excel.Worksheet)
Dim oRange as Excel.Range
oRange = oSheet.Range("A1")
oRange.Value = "Hello, world"
oRange.Font.Name = "Verdana"
oExcel.Visible = True
There you go, job done! Not the most exciting of code, admittedly, but hey, it's a starting point! My next objective is to put together a "utility" library for Excel, with the first thing that it does being a function to do the following:
1 - Takes an Excel Application object as a parameter
2 - (Force) closes any workbooks open in the application at the time it's called
3 - Creates a new workbook
4 - Removes all bar one of the worksheets in the workbook
2 - Returns a reference to the worksheet that is remaining as the functions return value.
