Export Data Grid to Excel in Silverlight 4.0


One of the great feature in Silverlight 4.0 is  COM interoperability, now your Silverlight application can talk with Office applications using Com Automation Factory. This feature requires a trusted application (elevated permissions). In this article I am going to explain how you can export your data from datagrid to excel spread sheet as  OOB (Out of browser) application using C# 4.0 magic keyword called “dynamic“.

You can Download the complete source code from here

Create a new Silverlgiht 4.0 project using VS 2010 and add Microsoft.CSharp as reference (for C# 4.0 dynamic keyword) and also the add the name space System.Runtime.InteropServices.Automation for  com interoperability

I am using a customer class with some getter and setter properties to bind the datagrid.

Customer Class


using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Runtime.InteropServices.Automation;

 public class Customer
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public bool IsSubscribed { get; set; }
 }

Method for Binding customer list to the Data Grid

 public ExportToExcel()
 {
 InitializeComponent();
 BindDataGrid();
 }

 void BindDataGrid()
 {
 int count = 10;
 List<Customer> customers = new List<Customer>();
 for (int i = 0; i < count; i++)
 {
 customers.Add(new Customer()
 {
 FirstName = "First Name " + i,
 LastName = "Last Name " + i,
 Age = i + 10,
 IsSubscribed = (i % 2 == 0)
 });
 }
 dgCustomers.ItemsSource = customers;
 }

Method for exporting data from data grid to excel spread sheet

 void GenerateSpreadSheet(object sender, RoutedEventArgs e)
 {
 int rowIndex = 1;
 int coulmnIndex = 1;

 try
 {
 dynamic excel = AutomationFactory.CreateObject("Excel.Application");

 excel.workbooks.Add();

 dynamic sheet = excel.ActiveSheet;

 for (int i = 0; i < dgCustomers.Columns.Count; ++i)
 {
 dynamic headerCell = sheet.Cells[rowIndex, coulmnIndex + i];
 headerCell.Value = dgCustomers.Columns[i].Header;
 headerCell.Font.Bold = true;
 headerCell.Interior.Color = 0xFF00;
 }

 foreach (Customer customer in dgCustomers.ItemsSource)
 {
 rowIndex++;

 //column 1
 dynamic cellFirstName = sheet.Cells[rowIndex, 1];
 cellFirstName.Value = customer.FirstName;
 cellFirstName.Font.Color = 003399;

 //column 2
 dynamic cellLastName = sheet.Cells[rowIndex, 2];
 cellLastName.Value = customer.LastName;
 cellLastName.Font.Color = 003399;

 //column 3
 dynamic cellAge = sheet.Cells[rowIndex, 3];
 cellAge.Value = customer.Age;
 cellAge.Font.Color = 003399;

 //column 4
 dynamic cellSubscribed = sheet.Cells[rowIndex, 4];
 cellSubscribed.Value = customer.IsSubscribed ? "Yes" : "No";
 cellSubscribed.Font.Color = 003399;
 }
 excel.Visible = true;
 }
 catch (Exception ex)
 {
 MessageBox.Show("Error generating excel: " + ex.Message);
 }
 }

The xaml code creates a data grid and a button

<Grid x:Name="LayoutRoot" Background="White">
 <Grid.RowDefinitions>
 <RowDefinition Height="350"></RowDefinition>
 <RowDefinition Height="5"></RowDefinition>
 <RowDefinition Height="25"></RowDefinition>
 <RowDefinition Height="*"></RowDefinition>
 </Grid.RowDefinitions>
 <my:DataGrid x:Name="dgCustomers" Grid.Row="0" AutoGenerateColumns="True" HeadersVisibility="All"
 RowBackground="Azure" AlternatingRowBackground="LightSteelBlue" ColumnWidth="85" RowHeight="30">
 </my:DataGrid>
 <Button  Grid.Row="2" Content="Export To Excel" Height="25" Width="120" Name="btnExportExcel" Click="GenerateSpreadSheet"  />
 </Grid>

Out of Browser set up

It is really easy to make a Silverlight applicaton as run out of browser mode. Right click the Silverlight project, select properties and check the ENABLE RUNNING APPLICATION OUT OF THE BROWSER.

Elevated permissions (Trusted Application)

Right click Silverlight Project – > Select Properties – > Click Out-Of-Browser Settings

You can Download the complete source code from here

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Advertisements