C# – WPF – Generate an Excel file with WPF

In the current article I proudly present a simple application, which creates a simple Excel file from XAML. In the example I present I am using Excel 2010 as this is my current version. In order to be able to create an excel application from WPF, we should enable the usage of some COM libraries . This is done through the following steps:

1. Go to “References” and click the right button -> Add Reference;

2. In the menu which appears, select “Microsoft Excel 14.0 Object Library” (the library can vary depending on your excel version. Excel 14.0 is for Excel 2010. Here you may find the other excel versions. As you see – Excel 2007 is version 12.0, Excel 2013 is version 15.

3. Simply click “OK”.

references

 

After adding the COM library you get access to a few nice features. The XAML code of our application is simple – it is just a button with method. Anyway, here it comes:

With the code behind, taking care for the execution of the program, the code looks as follows:

What do we have here? From the beginning, a new namespace:

Then in the method for file generation we have something familiar for those who have code experience with VBA for Excel. With the first three lines we create an Excel application, make it visible and we maximize it. Then we create a workbook and we name it in the same line. The first worksheet of the workbook is also named. Thus, so far we have named the excel application (app), the workbook (wb) and the first worksheet (ws). Then we create a variable of type DateTime, naming it currentDate. Using the “ws.Range[“”] we set values for the different excel boxes. We use formulas and even a loop. At the end we save everything in the path “C\Temp\ and the file is named “vitoshacademy.xlsx”. The usage of double slash (“\\”) is needed, because the single one acts as a comment in C#, and the double one neutralizes it.

In short, that is it. If you want to see this example, you may try it out here – ExcelInWPF.

About

A VBA Developer.

Tagged with: , , , , , , ,