How to Export Data grid Data in Excel Format in Silverlight 4?

 

 

How to Export Data grid Data in Excel Format ?

 

 

Hai !!! Everyone Here is the Solution

First Create the Silverlight main page and Create Butoon and Data grid .....

 

xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

 

add this line and add xaml code.

In that data grid using WCF Service Display Datas from DataBase.... 
The in Button Click Event Write this line of code 


this.theDataGrid.Export(); 


Then Create one class file and rename it to DataGridExtensions.cs 

Then inside this paste this lines of code ...... 

DataGridExtensions.cs 
======================= 


public static void Export(this DataGrid dg) 
{ 
ExportDataGrid(dg); 
} 

public static void ExportDataGrid(DataGrid dGrid) 
{ 


SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|Excel XML (*.xml)|*.xml|Excel Spreadsheets (*.xls)|*.xls |All files (*.*)|*.*", FilterIndex = 1 }; 
string messageBoxText = "Do you want to save changes?"; 
string caption = "Processing...."; 
MessageBoxButton button = MessageBoxButton.OKCancel; 


if (objSFD.ShowDialog() == true) 
{ 
MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button); 

// Process message box results 
switch (result) 
{ 
case MessageBoxResult.Yes: 
// User pressed Yes button 
// ... 
break; 
case MessageBoxResult.No: 
// User pressed No button 
// ... 
break; 
case MessageBoxResult.Cancel: 
// User pressed Cancel button 
// ... 
break; 
} 
string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper(); 
StringBuilder strBuilder = new StringBuilder(); 
if (dGrid.ItemsSource == null) return; 
List lstFields = new List(); 
if (dGrid.HeadersVisibility == DataGridHeadersVisibility.Column || dGrid.HeadersVisibility == DataGridHeadersVisibility.All) 
{ 
foreach (DataGridColumn dgcol in dGrid.Columns) 
lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat)); 
BuildStringOfRow(strBuilder, lstFields, strFormat); 
} 
foreach (object data in dGrid.ItemsSource) 
{ 
lstFields.Clear(); 
foreach (DataGridColumn col in dGrid.Columns) 
{ 
string strValue = ""; 
Binding objBinding = null; 
if (col is DataGridBoundColumn) 
objBinding = (col as DataGridBoundColumn).Binding; 
if (col is DataGridTemplateColumn) 
{ 
//This is a template column... let us see the underlying dependency object 
DependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent(); 
FrameworkElement oFE = (FrameworkElement)objDO; 
FieldInfo oFI = oFE.GetType().GetField("TextProperty"); 
if (oFI != null) 
{ 
if (oFI.GetValue(null) != null) 
{ 
if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null) 
objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding; 
} 
} 
} 
if (objBinding != null) 
{ 
if (objBinding.Path.Path != "") 
{ 
PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path); 
if (pi != null) strValue = pi.GetValue(data, null).ToString(); 
} 
if (objBinding.Converter != null) 
{ 
if (strValue != "") 
strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString(); 
else 
strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString(); 
} 
} 
lstFields.Add(FormatField(strValue,strFormat)); 
} 
BuildStringOfRow(strBuilder, lstFields, strFormat); 
} 
StreamWriter sw = new StreamWriter(objSFD.OpenFile()); 
if (strFormat == "XML") 
{ 
//Let us write the headers for the Excel XML 
sw.WriteLine(""); 
sw.WriteLine(""); 
sw.WriteLine(""); 
sw.WriteLine(""); 
sw.WriteLine("Arasu Elango"); 
sw.WriteLine("" + DateTime.Now.ToLocalTime().ToLongDateString() + ""); 
sw.WriteLine("" + DateTime.Now.ToLocalTime().ToLongDateString() + ""); 
sw.WriteLine("Atom8 IT Solutions (P) Ltd.,"); 
sw.WriteLine("12.00"); 
sw.WriteLine(""); 
sw.WriteLine(""); 
sw.WriteLine(""); 

sw.Write(strBuilder.ToString()); 
if (strFormat == "XML") 

sw.WriteLine("



"); 
sw.WriteLine(""); 
sw.WriteLine(""); 
} 
sw.Close(); 
} 
} 
private static void BuildStringOfRow(StringBuilder strBuilder, List lstFields, string strFormat) 
{ 
switch (strFormat) 
{ 
case "XML": 
strBuilder.AppendLine(""); 
strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray())); 
strBuilder.AppendLine(""); 
break; 
case "CSV": 
strBuilder.AppendLine(String.Join(",", lstFields.ToArray())); 
break; 
} 
} 
private static string FormatField(string data, string format) 
{ 
switch (format) 
{ 
case "XML": 
return String.Format("{0}", data); 
case "CSV": 
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", "")); 
} 
return data; 
} 


Thats All finished. Now press f5 and run the Application it will generate the csv dile and xml file and excel file.... If you want to Save the file into server Page the just give Server Path where you want to Save your file and just save it in Server.. 

Here i shown how to export into Csv and XML and excel file and save it into Local system and you can preview it.... 

If anyone is having any other idea or any comments please post it here ... I will try to improve it/..... 

Its working fine for me....... 

Have fun............ 

Hope this application will help you to all. Thanks. 

Please post your valuable comments here if you like this. 


Thanks & Regards, 
Sanjay, 

Silverlight Developer