首先新建一个DataGrdiExtensions类,代码为:

 public static class DataGridExtensions{/// <summary>/// 导出dg中数据,成功返回true,失败返回false/// </summary>/// <param name="dg"></param>/// <returns></returns>public static bool Export(this DataGrid dg){return ExportDataGrid(dg);}/// <summary>/// 导出dGrid中数据,成功返回true,失败返回false/// </summary>/// <param name="dGrid"></param>/// <returns></returns>public static bool ExportDataGrid(DataGrid dGrid){bool exportOK = false;#region 导出数据try{SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|Excel XML (*.xml)|*.xml|All files (*.*)|*.*", FilterIndex = 1 };if (objSFD.ShowDialog() == true){string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();StringBuilder strBuilder = new StringBuilder();if (dGrid.ItemsSource == null) return false;List<string> lstFields = new List<string>();if (dGrid.HeadersVisibility == DataGridHeadersVisibility.Column || dGrid.HeadersVisibility == DataGridHeadersVisibility.All){foreach (DataGridColumn dgcol in dGrid.Columns)lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat));BuildStringOfRow(strBuilder, lstFields, strFormat);}foreach (object data in dGrid.ItemsSource){lstFields.Clear();foreach (DataGridColumn col in dGrid.Columns){string strValue = "";Binding objBinding = null;if (col is DataGridBoundColumn)objBinding = (col as DataGridBoundColumn).Binding;if (col is DataGridTemplateColumn){//This is a template column... let us see the underlying dependency objectDependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent();FrameworkElement oFE = (FrameworkElement)objDO;FieldInfo oFI = oFE.GetType().GetField("TextProperty");if (oFI != null){if (oFI.GetValue(null) != null){if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null)objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding;}}}if (objBinding != null){if (objBinding.Path.Path != ""){PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);if (pi != null) strValue = pi.GetValue(data, null).ToString();}if (objBinding.Converter != null){if (strValue != "")strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();elsestrValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();}}lstFields.Add(FormatField(strValue, strFormat));}BuildStringOfRow(strBuilder, lstFields, strFormat);}StreamWriter sw = new StreamWriter(objSFD.OpenFile(), System.Text.Encoding.Unicode);if (strFormat == "XML"){//Let us write the headers for the Excel XMLsw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");sw.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");sw.WriteLine("<Author>Arasu Elango</Author>");sw.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");sw.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");sw.WriteLine("<Company>Atom8 IT Solutions (P) Ltd.,</Company>");sw.WriteLine("<Version>12.00</Version>");sw.WriteLine("</DocumentProperties>");sw.WriteLine("<Worksheet ss:Name=\"Silverlight Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");sw.WriteLine("<Table>");}sw.Write(strBuilder.ToString());if (strFormat == "XML"){sw.WriteLine("</Table>");sw.WriteLine("</Worksheet>");sw.WriteLine("</Workbook>");}sw.Close();exportOK = true;}}catch (Exception ex){exportOK = false;MessageBox.Show("保存失败:"+ex.Message);}#endregionreturn exportOK;}/// <summary>/// 设置datagrid中每一行的数据内容/// </summary>/// <param name="strBuilder"></param>/// <param name="lstFields"></param>/// <param name="strFormat"></param>private static void BuildStringOfRow(StringBuilder strBuilder, List<string> lstFields, string strFormat){switch (strFormat){case "XML":strBuilder.AppendLine("<Row>");strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));strBuilder.AppendLine("</Row>");break;case "CSV":strBuilder.AppendLine(String.Join("\t", lstFields.ToArray()));break;}}/// <summary>/// 设置字符串输出格式/// </summary>/// <param name="data"></param>/// <param name="format"></param>/// <returns></returns>private static string FormatField(string data, string format){switch (format){case "XML":return String.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>", data);case "CSV":return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));}return data;}}

导出数据时,只需要调用方法:datagrid.Export()即可

转载于:https://www.cnblogs.com/jiangu66/p/3228541.html

silverlight中datagrid数据到处excel相关推荐

  1. DataTable中的数据导出Excel文件

    DataTable中的数据导出Excel文件 View Code ///<summary> /// 将DataTable中的数据导出到指定的Excel文件中 ///</summary ...

  2. C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

    其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...

  3. python excel模板 生成excel表格_python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图...

    python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 #coding=utf-8 from openpyxl importload_workbookfro ...

  4. 在vue中把数据导出Excel文件

    在vue中把数据导出Excel文件 第一次尝试写文章 在vue中把数据导出成Excel格式的文件,话不多,上代码: 第一步我们要先安装几个集成的插件 npm install -S file-saver ...

  5. 如何在 Vue 中导出数据至 Excel 表格 - 卡拉云

    本文首发:<如何在 Vue 中导出数据至 Excel 表格 - 卡拉云> 我们经常需要在 Vue 搭建的后台管理系统里导出数据到 Excel / CSV ,方便我们将数据共享给其他同学或在 ...

  6. ASP.NET中数据库数据导入Excel并打印

    众所周知,WEB上的打印是比较困难的,常见的WEB上打印的方法大概有三种: 1.直接利用IE的打印功能.一般来说,这种方法可以做些扩展,而不是单单的调用javascript:print()这样简单,比 ...

  7. python导入excel数据-如何把python中的数据导入excel

    python将数据导入excel的方法:1.在python官网下载xlrd第三方库:2.利用xlrd中的open_workbook函数读入excel文件,即可在python中导入excel数据. 一. ...

  8. .net中从GridView中导出数据到excel(详细)

    1,创建数据源 找到要导出的GridView中的数据. 2,重写VerifyRenderingInServerForm方法. public override void VerifyRenderingI ...

  9. 将页面中表格数据导出excel格式的文件(vue)

    近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...

  10. ASP.NET中GridView数据导出EXCEL小结

    本周按业务部门的要求,做一个客户拜访登记管理的小程序(B/S模式),在这里面用到了GridView来显示根据条件查询到的数据,但业务部门同时要求数据要导出为EXCEL方面使用,在网上查找了很多资料,汇 ...

最新文章

  1. fixture详细介绍-作为参数传入,error和failed区别
  2. 查询name和age当name相同时选择age最大的
  3. 百度的卡尔曼滤波的解释
  4. python 取array并集_Python内置数据结构原理与性能简易分析
  5. html出现滚动条页面闪动,CSS3 calc实现滚动条出现页面不跳动闪动
  6. 数据结构 3优先队列(堆)
  7. C#实现Winform程序自动进行版本升级更新
  8. 穿行大街小巷 寻找“没落儿”的扬州
  9. Simulink代码生成:通过Legacy Code Tool集成C函数
  10. 20doing 动名词
  11. dede织梦后台页面及功能修改及精简操作方法
  12. win10安装并配置node.js
  13. 带你领略MotionLayout的魅力(中)
  14. 公共场所的标志和说明英文表达100例
  15. 文本检测算法性能对比
  16. 单线激光雷达的外参标定方法
  17. 一颗红心,三手准备,分别基于图片(img)/SCSS(样式)/SVG动画实现动态拉轰的点赞按钮特效
  18. 英语的加减乘除怎么计算机,用英语表示加减乘除法的用法
  19. Oracle索引梳理系列(十)- 直方图使用技巧及analyze table操作对直方图统计的影响(谨慎使用)...
  20. 【Kaldi 新手入门】手把手教你搭建简易英文数字ASR系统

热门文章

  1. lf 前后端分离 (5) 优惠券
  2. vue项目的安装与启动
  3. Scrapy爬取hupu论坛标题统计数量并生成wordcloud
  4. 我常用的那些 Git 命令
  5. 云计算项目实战——系统API模块
  6. svn 查看版本历史时。Item is not readable svn: 条目不可读
  7. ***_ha_高可用_链路备份
  8. pooling层如何反向传播? 很简单
  9. 六、基于UDP的服务器端/客户端
  10. iQOO5G手机卡槽公布