说明:这个方法是从网上找到的,但是原来的方法没有考虑到绑定的字段是“自定义类型属性的属性” 以及更深(我在说啥呢。。)。我动了一些手脚完善了一点。
备注1:还有就是找不到原来的网址了。。
备注2:我先在微软战车上的做了留底。
两个方法(做成扩展方法,调用方便)
public static string ExportDataGrID( this DataGrID grID, bool withheaders){
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( "\t\n");
foreach (Object data in source)
{
List< string> csvRow = string>();
foreach (DataGrIDColumn col in grID.Columns)
{
is DataGrIDBoundColumn)
{
binding = (col as DataGrIDBoundColumn).Binding;
colPath = binding.Path.Path;
string[] pathList = colPath.Split('.'); //此处往下做了修改
object currentData = data;
int count = 0;
foreach ( string item in pathList)
{
propInfo = currentData.GetType().GetProperty(item);
if (propInfo == null) break;
count++;
if (count == pathList.Count())
{
csvRow.Add(FormatCSVFIEld(propInfo.GetValue(currentData,255)">null).GetTrimstring()));
break;
}
else
{
currentData = propInfo.GetValue(currentData,255)">null);
}
}
}
}
strBuilder
.Append( .Append( "\t\n");
}
return strBuilder.ToString();
}
private string FormatCSVFIEld( string data)
{
//return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
return String.Format( "\t{0}", data.Replace( "\"", "\t\n"));
}
使用示范:
voID btnExcelExport_Click( object sender, RoutedEventArgs e){
string data = grIDOrderList.ExportDataGrID( true); //调用函数
byte[] tmp;
tmp = EnCoding.Unicode.GetBytes(data);
SavefileDialog sfd = new SavefileDialog()
{
DefaultExt = "csv",
Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true)
{
using (System.IO.Stream stream = sfd.Openfile())
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, EnCoding.Unicode, 30))
{
writer.Write(data);
writer.Close();
}
stream.Close();
}
}
}
本文来自往事如锋的博客,原文地址:http://www.cnblogs.com/xtechnet/archive/2011/05/28/silverlightToExcel.HTML
总结以上是内存溢出为你收集整理的Silverlight导出excel的另一种方式全部内容,希望文章能够帮你解决Silverlight导出excel的另一种方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)