How To Export Datagrid Content Into Excel, CSV Or XML Format Using Silverlight4 ?


Introduction:

Hello! Microsoft introduced Silverlight 4 which is the open door to modern application development. It's rich XAML UI and strong C# / VB backend code makes it more powerful and enjoyable for professional microsoft developers. Many companies are using Silverlight for their product development. Another catchy thing is Silverlight supports animation kind of browser based flash animation, which is just simple using XAML code. I am beginner of Silverlight based development and came across a task where i need to implement CSV Export using Silverlight 4. I thought of documenting and posting it here so it may also help other beginner like me. You may also do googling if this post is not fulfilling your requirement.

First thing you need to create a basic Silverlight main page and drag and drop button, Datagrid etc. into it. Add below line into your XAML page.



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

<my:datagrid alternatingrowbackground="Beige" name="theDataGrid" span=""></my>


Click on datagrid and you need to call WCF web service to fetch data from database and bind into the grid to display. Please not Silverlight application require WCF web service to interact with Database and get data. In the button click event write below code.


this.theDataGrid.Export();


Then create a class file and rename it to DataGridExtensions.cs. Paste below into the same class.

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;
 }



That's all. We are done. Now press F5 and run the application. This small app will allow you to generate CSV, Excel, XML format etc. If you would like to save the file into different server location you make changes to the server path and save as needed. In this short post show you how to export data into CSV/XML/Excel file and store into local path. Please use comment box to share if you have different solution to achieve the same task. It help me as well as other needed developers to improve on.

Hope it helps. Thanks!

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions