Free mag vol1 | Page 676

CHAPTER 16  DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME The Click event handler for the “Export Current Inventory to Excel” button is the heart of this example. Using the Add Reference dialog box, add a reference to the Microsoft.Office.Interop.Excel.dll primary interop assembly (as shown previously in Figure 16-7). Add the following namespace alias to the form’s primary code file. Be aware that this is not mandatory to define an alias when interacting with COM libraries. However, by doing so, you have a handy qualifier for all of the imported COM objects, which is very handy if some of these COM objects have names that would clash with your .NET types. // Create an alias to the Excel object model. using Excel = Microsoft.Office.Interop.Excel; Implement this button Click event hander to call a private helper function named ExportToExcel(), like so: private void btnExportToExcel_Click(object sender, EventArgs e) { ExportToExcel(carsInStock); } Because you imported the COM library using Visual Studio, the PIA has been automatically configured so that the used metadata will be embedded into the .NET application (recall the role of the Embed Interop Types property). Therefore, all COM Variants are realized as dynamic data types. Furthermore, you can make use of C# optional arguments and named arguments. This being said, consider the following implementation of ExportToExcel(): static void ExportToExcel(List carsInStock) { // Load up Excel, then make a new empty workbook. Excel.Application excelApp = new Excel.Application(); excelApp.Workbooks.Add(); // This example uses a single workSheet. Excel._Worksheet workSheet = excelApp.ActiveSheet; // Establish column headings in cells. workSheet.Cells[1, "A"] = "Make"; workSheet.Cells[1, "B"] = "Color"; workSheet.Cells[1, "C"] = "Pet Name"; // Now, map all data in List to the cells of the spreadsheet. int row = 1; foreach (Car c in carsInStock) { row++; workSheet.Cells[row, "A"] = c.Make; workSheet.Cells[row, "B"] = c.Color; workSheet.Cells[row, "C"] = c.PetName; } // Give our table data a nice look and feel. workSheet.Range["A1"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); 618