gpt4 book ai didi

c# - Silverlight 数据网格 : Export to excel or csv

转载 作者:IT王子 更新时间:2023-10-29 04:30:38 26 4
gpt4 key购买 nike

有没有一种方法可以将我的 Silverlight DataGrid 数据导出到 excel 或 csv?

我在网上搜索但找不到任何示例!

非常感谢

最佳答案

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

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("\n", "")
.Replace("\r", "")
);
}

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("\r\n");

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("\r\n");
}


return strBuilder.ToString();
}

关于c# - Silverlight 数据网格 : Export to excel or csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/304322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com