Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Exporting DataGrid to Excel

$
0
0

I am Exporting data from DataGrid in WPF to Excel. This is the code I am using:

public string ExportDataGrid(bool withHeaders, Microsoft.Windows.Controls.DataGrid grid) 
{
    string colPath;
    System.Reflection.PropertyInfo propInfo;
    System.Windows.Data.Binding binding;
    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(FormatCSVField(col.Header.ToString()));
        }
    });

    strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
    foreach (Object data in source)
    {
        List<string> csvRow = new List<string>();
        foreach (Microsoft.Windows.Controls.DataGridColumn col in grid.Columns)
        {
            if (col is Microsoft.Windows.Controls.DataGridBoundColumn)
            { 
                binding = (col as Microsoft.Windows.Controls.DataGridBoundColumn).Binding;
                colPath = binding.Path.Path;
                propInfo = data.GetType().GetProperty(colPath);
                if (propInfo != null)
                {
                    if (propInfo.GetValue(data, null) != null)
                    {
                        csvRow.Add(FormatCSVField(propInfo.GetValue(data, null).ToString()));
                    }
                    else
                    {
                        csvRow.Add(string.Empty);
                    }
                }
            }
        }
        strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
    }

    return strBuilder.ToString();
}

I have it working in Silverlight, but I can't make it to work in WPF.

The error message I am getting in this line: binding = (col as Microsoft.Windows.Controls.DataGridBoundColumn).Binding; is:

Error 3 Cannot implicitly convert type 'System.Windows.Data.BindingBase' to 'System.Windows.Data.Binding'. An explicit conversion exists (are you missing a cast?) C:\Users\lpmo\My Programs\DIAGONAL\Aplicaciones.NET\Control\Control\MainWindow.xaml.cs 712 35 Control

Anybody knows why?

Thanks a lot!!
Lina


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>