CHAPTER 16 DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME
// Save the file, quit Excel, and display message to user.
workSheet.SaveAs(string.Format(@"{0}\Inventory.xlsx", Environment.CurrentDirectory));
excelApp.Quit();
MessageBox.Show("The Inventory.xslx file has been saved to your app folder",
"Export complete!");
}
This method begins by loading Excel into memory; however, you won’t see it visible on your
computer desktop. For this application, you are only interested in using the internal Excel object model.
However, if you do want to actually display the UI of Excel, update your method with this additional line
of code:
static void ExportToExcel(List carsInStock)
{
// Load up Excel, then make a new empty workbook.
Excel.Application excelApp = new Excel.Application();
// Go ahead and make Excel visible on the computer.
excelApp.Visible = true;
...
}
After you create an empty worksheet, you add three columns that are named similar to the
properties of the Car class. Then, you fill the cells with the data of the List, and save your file under
the (hardcoded) name Inventory.xlsx.
At this point, if you run your application, add a few new records, and export your data to Excel, you
will then be able to open up the Inventory.xlsx file, which will be saved to the \bin\Debug folder of your
Windows Forms application. Figure 16-10 shows a possible export.
Figure 16-10. Exporting your data to an Excel file
619