Alex Rivera | Logout

Silverlight DataGrid: Export to excel or csv

Asked 2008-11-20T04:21:42.240
22

Is there a way I can export my Silverlight DataGrid data to excel or csv?

I searched the web but can't find any examples!

Thanks a lot

Edit
Report

1 Answer

1

Those solutions didn't work for me, so I modified them to one that worked. (My solution doesn't require quotes around fields, so I left out the FormatCSVField function)

    public void SaveAs(string csvPath)
    {
        string data = ExportDataGrid(true, _flexGrid);
        StreamWriter sw = new StreamWriter(csvPath, false, Encoding.UTF8);
        sw.Write(data);
        sw.Close();
    }

    public string ExportDataGrid(bool withHeaders, Microsoft.Windows.Controls.DataGrid grid) 
    {
        System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
        System.Collections.IEnumerable source = (grid.ItemsSource as System.Collections.IEnumerable);

        if (source == null) return "";

        List<string> headers = new List<string>();

        grid.Columns.ToList().ForEach(col =>
        {
            if (col is Microsoft.Windows.Controls.DataGridBoundColumn)
            {
                headers.Add(col.Header.ToString());
            }
        });

        strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
        foreach (Object data in source)
        {
            System.Data.DataRowView d = (System.Data.DataRowView)data;
            strBuilder.Append(String.Join(",", d.Row.ItemArray)).Append("\r\n");
        }

        return strBuilder.ToString();
    }
answered 2011-03-07T16:43:10.410

Your Answer