且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Silverlight DataGrid:导出到 excel 或 csv

更新时间:2021-11-02 09:13:43

Silverlight 3 更改了此问题的答案,因为它使用户能够在用户桌面上指定的位置创建文件.我改编了 DaniCE 提交的代码,将事情分成几种方法以提高可读性,并使用了 Excel 应该识别的松散定义的 CSV 格式.

Silverlight 3 changes the answer to this question because it gives the ability of the user to create a file on the user's desktop in a location that they specify. I adapted the code submitted by DaniCE, split things into a few methods for readability and am using a loosely defined CSV format that Excel should recognize.

private void exportHistoryButton_Click(object sender, RoutedEventArgs e) 
{
    string data = ExportDataGrid(true, historyDataGrid);
    SaveFileDialog sfd = new SaveFileDialog()
    {
    DefaultExt = "csv",
    Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
    FilterIndex = 1
    };
    if (sfd.ShowDialog() == true)
    {
    using (Stream stream = sfd.OpenFile())
    {
        using (StreamWriter writer = new StreamWriter(stream)) {
        writer.Write(data);
        writer.Close();
        }
        stream.Close();
    }
    }
}

private string FormatCSVField(string data) {
    return String.Format(""{0}"",
        data.Replace(""", """"")
        .Replace("
", "")
        .Replace("
", "")
        );
}

public string ExportDataGrid(bool withHeaders, DataGrid grid)
{
    string colPath;
    System.Reflection.PropertyInfo propInfo;
    System.Windows.Data.Binding binding;
    System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
    System.Collections.IList source = (grid.ItemsSource as System.Collections.IList);
    if (source == null)
    return "";

    List<string> headers = new List<string>();
    grid.Columns.ToList().ForEach(col => {
    if (col is DataGridBoundColumn){
        headers.Add(FormatCSVField(col.Header.ToString()));
    }
    });
    strBuilder
    .Append(String.Join(",", headers.ToArray()))
    .Append("
");

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


    return strBuilder.ToString();
}