silverlight中datagrid数据到处excel
首先新建一个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相关推荐
- DataTable中的数据导出Excel文件
DataTable中的数据导出Excel文件 View Code ///<summary> /// 将DataTable中的数据导出到指定的Excel文件中 ///</summary ...
- C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel
其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...
- python excel模板 生成excel表格_python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图...
python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 #coding=utf-8 from openpyxl importload_workbookfro ...
- 在vue中把数据导出Excel文件
在vue中把数据导出Excel文件 第一次尝试写文章 在vue中把数据导出成Excel格式的文件,话不多,上代码: 第一步我们要先安装几个集成的插件 npm install -S file-saver ...
- 如何在 Vue 中导出数据至 Excel 表格 - 卡拉云
本文首发:<如何在 Vue 中导出数据至 Excel 表格 - 卡拉云> 我们经常需要在 Vue 搭建的后台管理系统里导出数据到 Excel / CSV ,方便我们将数据共享给其他同学或在 ...
- ASP.NET中数据库数据导入Excel并打印
众所周知,WEB上的打印是比较困难的,常见的WEB上打印的方法大概有三种: 1.直接利用IE的打印功能.一般来说,这种方法可以做些扩展,而不是单单的调用javascript:print()这样简单,比 ...
- python导入excel数据-如何把python中的数据导入excel
python将数据导入excel的方法:1.在python官网下载xlrd第三方库:2.利用xlrd中的open_workbook函数读入excel文件,即可在python中导入excel数据. 一. ...
- .net中从GridView中导出数据到excel(详细)
1,创建数据源 找到要导出的GridView中的数据. 2,重写VerifyRenderingInServerForm方法. public override void VerifyRenderingI ...
- 将页面中表格数据导出excel格式的文件(vue)
近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...
- ASP.NET中GridView数据导出EXCEL小结
本周按业务部门的要求,做一个客户拜访登记管理的小程序(B/S模式),在这里面用到了GridView来显示根据条件查询到的数据,但业务部门同时要求数据要导出为EXCEL方面使用,在网上查找了很多资料,汇 ...
最新文章
- fixture详细介绍-作为参数传入,error和failed区别
- 查询name和age当name相同时选择age最大的
- 百度的卡尔曼滤波的解释
- python 取array并集_Python内置数据结构原理与性能简易分析
- html出现滚动条页面闪动,CSS3 calc实现滚动条出现页面不跳动闪动
- 数据结构 3优先队列(堆)
- C#实现Winform程序自动进行版本升级更新
- 穿行大街小巷 寻找“没落儿”的扬州
- Simulink代码生成:通过Legacy Code Tool集成C函数
- 20doing 动名词
- dede织梦后台页面及功能修改及精简操作方法
- win10安装并配置node.js
- 带你领略MotionLayout的魅力(中)
- 公共场所的标志和说明英文表达100例
- 文本检测算法性能对比
- 单线激光雷达的外参标定方法
- 一颗红心,三手准备,分别基于图片(img)/SCSS(样式)/SVG动画实现动态拉轰的点赞按钮特效
- 英语的加减乘除怎么计算机,用英语表示加减乘除法的用法
- Oracle索引梳理系列(十)- 直方图使用技巧及analyze table操作对直方图统计的影响(谨慎使用)...
- 【Kaldi 新手入门】手把手教你搭建简易英文数字ASR系统