Click here to Skip to main content
11,920,772 members (58,096 online)
Click here to Skip to main content
Add your own
alternative version


52 bookmarked

Export Silverlight DataGrid to Excel XML/CSV

, 1 Dec 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article explains how to export the contents of a DataGrid to Excel/CSV.


There are several reasons for the end user to export data from an application into an Excel compatible format (mostly for further analysis/usage or data). This article explains how to include data export capability to Silverlight DataGrid.


I am working on migrating some ASP.NET code to a Silverlight application. One of the features that I felt lacking in Silverlight is the ability to export the contents of a DataGrid to the end user. To address this issue, I created an extension for DataGrid control. When the attached file (DataGridExtensions.cs) is included in a project, the "Export" extension is automatically made available to all the DataGrid controls used in the project.

Using the code

This module exposes two methods:

  • Export (this DataGrid dg) - extends the DataGrid control by providing the export functionality.
  • ExportDataGrid (DataGrid dGrid) - this method is internally called by the "Export" DataGrid extension. However, this method can be directly called too.
public static void Export(this DataGrid dg)
public static void ExportDataGrid(DataGrid dGrid)
    SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "csv", 
        Filter = "CSV Files (*.csv)|*.csv|Excel XML (*.xml)|*.xml|All files (*.*)|*.*", 
        FilterIndex = 1 };
    if (objSFD.ShowDialog() == true)
        string strFormat = 
          objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
        StringBuilder strBuilder = new StringBuilder();
        if (dGrid.ItemsSource == null) return;
        List<string> lstFields = new List<string>();
        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)
            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 = 
                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, 
                            strValue = objBinding.Converter.Convert(data, 
                              typeof(string), objBinding.ConverterParameter, 
            BuildStringOfRow(strBuilder, lstFields, strFormat);
        StreamWriter sw = new StreamWriter(objSFD.OpenFile());
        if (strFormat == "XML")
            //Let us write the headers for the Excel XML
            sw.WriteLine("<?xml version=\"1.0\" " + 
            sw.WriteLine("<?mso-application progid" + 
            sw.WriteLine("<Workbook xmlns=\"urn:" + 
            sw.WriteLine("<DocumentProperties " + 
                         "xmlns=\"urn:schemas-microsoft-com:" + 
            sw.WriteLine("<Author>Arasu Elango</Author>");
            sw.WriteLine("<Created>" +  
                         DateTime.Now.ToLocalTime().ToLongDateString() + 
            sw.WriteLine("<LastSaved>" + 
                         DateTime.Now.ToLocalTime().ToLongDateString() + 
            sw.WriteLine("<Company>Atom8 IT Solutions (P) " + 
            sw.WriteLine("<Worksheet ss:Name=\"Silverlight Export\" " + 
        if (strFormat == "XML")

The ExportDataGrid method prompts to the user to select the output save file name. Based on the user selection, the method determines the format to save -- XML or CSV. The Excel XML format used is not compatible with Microsoft Excel 2003 or earlier.

The row contents are built by a method named BuildStringOfRow.

private static void BuildStringOfRow(StringBuilder strBuilder, 
        List<string> lstFields, string strFormat)
    switch (strFormat)
        case "XML":
            strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));
        case "CSV":
            strBuilder.AppendLine(String.Join(",", lstFields.ToArray()));

The above method builds the row contents string as per the output format. Formatting of individual fields is done by a method named FormatField.

private static string FormatField(string data, string format)
    switch (format)
        case "XML":
            return String.Format("<Cell><Data ss:Type=\"String" + 
               "\">{0}</Data></Cell>", data);
        case "CSV":
            return String.Format("\"{0}\"", 
              data.Replace("\"", "\"\"\"").Replace("\n", 
              "").Replace("\r", ""));
    return data;

The FormatField method returns the data formatted as per the output format.

How to use

After including the attached code (DataGridExtensions.cs) to your project, you can initiate the export of the DataGrid contents by calling the Export() method of the DataGrid. For example, if the DataGrid name is objDataGrid, you will be calling objDataGrid.Export() to invoke the export.

Points of interest

This code generates the Excel file in XML format. I found exporting in XML much easier than exporting into the XLS or XLSX format.


  • Version 1 - December 1, 2009.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Architect Atom8 IT Solutions (P) Ltd
India India
I have been programming since 1991. I consider programming as my passion. I founded Atom8 IT Solutions (P) Ltd., in April 2009 and have been developing applications in Microsoft Technologies (mainly C#, Silverlight).

My specialization has been on the US healthcare domain (Medical Transcription, Patient Financial Services, EMRs).

You may also be interested in...

Comments and Discussions

QuestionOnly exports the data from one page(current page) and not all items in the datasource Pin
chaiwa24-Aug-15 5:53
memberchaiwa24-Aug-15 5:53 
Questionproblem in using the code in WPF Pin
Member 108307014-Jun-14 23:03
memberMember 108307014-Jun-14 23:03 
QuestionCool stuff! Pin
Nick Gray (Techno Crusaders)25-May-14 18:27
memberNick Gray (Techno Crusaders)25-May-14 18:27 
Question.xlsx Pin
Angela 1029384829-Jan-14 2:25
memberAngela 1029384829-Jan-14 2:25 
QuestionConvert Pin
Angela 1029384828-Jan-14 0:21
memberAngela 1029384828-Jan-14 0:21 
QuestionThanks Pin
Ravin Singh D23-Jan-14 7:49
memberRavin Singh D23-Jan-14 7:49 
QuestionNull reference Exception Pin
Member 970420616-Jun-13 23:40
memberMember 970420616-Jun-13 23:40 
GeneralMy vote of 5 Pin
Yasodha.eng29-Apr-13 0:22
memberYasodha.eng29-Apr-13 0:22 
QuestionTo hide some selected columns in the exported file Pin
meetprabhum31-Oct-12 0:07
membermeetprabhum31-Oct-12 0:07 
GeneralIf the characters is chinese , it will appear garbled. Pin
starrycheng2-Aug-12 21:22
memberstarrycheng2-Aug-12 21:22 
QuestionProblem Pin
aa_rojasm25-Jun-12 7:45
memberaa_rojasm25-Jun-12 7:45 
GeneralRe: Problem Pin
SpeedyCoder1-Jul-12 10:41
memberSpeedyCoder1-Jul-12 10:41 
QuestionExport Silverlight DataGrid to Excel XML/CSV Pin
Vikramdcecse8-Jun-12 8:58
memberVikramdcecse8-Jun-12 8:58 
QuestionEmpty Pin
Member 875655724-Mar-12 1:45
memberMember 875655724-Mar-12 1:45 
GeneralMy vote of 5 Pin
EderM222-Feb-12 8:21
memberEderM222-Feb-12 8:21 
QuestionHow to Export Images to excel in silver light Pin
Member 401717417-Feb-12 4:17
memberMember 401717417-Feb-12 4:17 
QuestionHow to have multiple worksheets Pin
S.R.H12-Feb-12 23:19
memberS.R.H12-Feb-12 23:19 
GeneralMy vote of 5 Pin
Shilpa from Mysore2-Feb-12 0:21
memberShilpa from Mysore2-Feb-12 0:21 
QuestionNice work, thanks! Pin
Member 839692426-Dec-11 14:28
memberMember 839692426-Dec-11 14:28 
QuestionChanges to work with nullable types Pin
JohhLewis21-Dec-11 4:37
memberJohhLewis21-Dec-11 4:37 
GeneralMy vote of 5 Pin
T. Abdul Rahman9-Oct-11 22:03
memberT. Abdul Rahman9-Oct-11 22:03 
Suggestionnested properties Pin
rafa123413-Sep-11 6:24
memberrafa123413-Sep-11 6:24 
GeneralRe: nested properties Pin
awgtek11-Sep-12 11:03
memberawgtek11-Sep-12 11:03 
GeneralNumber cells Pin
memberLARS MORTEN NYGAARD8-May-11 22:59 
QuestionColumn Headers Pin
childg7-Feb-11 12:59
memberchildg7-Feb-11 12:59 
AnswerRe: Column Headers Pin
raelango7-Feb-11 16:38
memberraelango7-Feb-11 16:38 
GeneralMy vote of 5 Pin
technette27-Jan-11 16:24
membertechnette27-Jan-11 16:24 
GeneralMy vote of 5 Pin
Member 47608858-Dec-10 21:51
memberMember 47608858-Dec-10 21:51 
GeneralGreat sample but fails Pin
dwf200824-Nov-10 6:53
memberdwf200824-Nov-10 6:53 
GeneralRe: Great sample but fails Pin
raelango24-Nov-10 22:38
memberraelango24-Nov-10 22:38 
GeneralMy vote of 5 Pin
mcaayyappan23-Sep-10 1:18
membermcaayyappan23-Sep-10 1:18 
GeneralPlease advise... [modified] Pin
AlexWang201021-Sep-10 12:00
memberAlexWang201021-Sep-10 12:00 
GeneralHi Pin
Naga Sridhar Madiraju29-Aug-10 22:41
memberNaga Sridhar Madiraju29-Aug-10 22:41 
Questiondatagrid with datapager Pin
Patrick Ladd10-Aug-10 8:52
memberPatrick Ladd10-Aug-10 8:52 
AnswerRe: datagrid with datapager Pin
livinho3818-Aug-10 0:30
memberlivinho3818-Aug-10 0:30 
GeneralRe: datagrid with datapager Pin
raelango18-Aug-10 0:56
memberraelango18-Aug-10 0:56 
GeneralRe: datagrid with datapager Pin
uscgc7248-Sep-10 5:43
memberuscgc7248-Sep-10 5:43 
AnswerRe: datagrid with datapager Pin
lakson25-Dec-10 3:05
memberlakson25-Dec-10 3:05 
GeneralOutstanding! One comment to handle NULL values in data... Pin
Noah Wollowick21-Jul-10 14:41
memberNoah Wollowick21-Jul-10 14:41 
Questionwhich version of SL is this example? Pin
zondymothoa13-Jun-10 22:49
memberzondymothoa13-Jun-10 22:49 
AnswerRe: which version of SL is this example? Pin
raelango13-Jun-10 23:24
memberraelango13-Jun-10 23:24 
GeneralReplacing escape characters Pin
seonsoo25-May-10 23:54
memberseonsoo25-May-10 23:54 
GeneralOutstanding! Pin
David_Murdoch30-Apr-10 13:24
memberDavid_Murdoch30-Apr-10 13:24 
GeneralRe: Outstanding! Pin
raelango30-Apr-10 22:03
memberraelango30-Apr-10 22:03 
Generalnice work dude Pin
sachinblore27-Apr-10 8:52
membersachinblore27-Apr-10 8:52 
Generalno me graba la informacion en los controles Pin
ccmmasi22-Apr-10 13:16
memberccmmasi22-Apr-10 13:16 
GeneralRe: no me graba la informacion en los controles Pin
raelango22-Apr-10 21:28
memberraelango22-Apr-10 21:28 
GeneralException if datacell is null Pin
francesconuma2-Mar-10 1:46
memberfrancesconuma2-Mar-10 1:46 
GeneralRe: Exception if datacell is null Pin
raelango2-Mar-10 2:38
memberraelango2-Mar-10 2:38 
QuestionCan the file be give a name in code? Pin
2 Rocks17-Feb-10 9:08
member2 Rocks17-Feb-10 9:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151120.1 | Last Updated 1 Dec 2009
Article Copyright 2009 by raelango
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid