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 object
DependencyObject 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();
else
strValue = 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 XML
sw.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);
}
#endregion return 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()即可
silverlight中datagrid数据到处excel的更多相关文章
- 利用Aspose.Cells完成easyUI中DataGrid数据的Excel导出功能
我准备在项目中实现该功能之前,google发现大部分代码都是利用一般处理程序HttpHandler实现的服务器端数据的Excel导出,但是这样存在的问题是ashx读取的数据一般都是数据库中视图的数据, ...
- silverlight中DataGrid数据高亮显示
效果如图所示, <UserControl xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.W ...
- 将Oracle数据库中的数据写入Excel
将Oracle数据库中的数据写入Excel 1.准备工作 Oracle数据库"TBYZB_FIELD_PRESSURE"表中数据如图: Excel模板(201512.xls): 2 ...
- C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel
其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...
- 对.NET中导出数据到EXCEL的几种方法探讨
最近在做一个报表系统的时候,需要把DATASET中的数据导到EXCEL当中,于是在网上找了一遍,发现了好几种方法,本来以为应该差不多,但后来经过一一试用后,发现在性能上真的差别很大,现在就介绍一下,同 ...
- python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图
python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 # coding=utf-8 from openpyxl import load_workbook ...
- 手把手教你springboot中导出数据到excel中
手把手教你springboot中导出数据到excel中 问题来源: 前一段时间公司的项目有个导出数据的需求,要求能够实现全部导出也可以多选批量导出(虽然不是我负责的,我自己研究了研究),我们的项目是x ...
- .net中从GridView中导出数据到excel(详细)
1,创建数据源 找到要导出的GridView中的数据. 2,重写VerifyRenderingInServerForm方法. public override void VerifyRenderingI ...
- ASP.Net MVC中数据库数据导出Excel,供HTTP下载(转)
转自http://www.cnblogs.com/hipo/archive/2012/03/13/2394019.html 一.关于下载 一般对下载权限有没有限制,或安全性要求不高的情况下,基于web ...
随机推荐
- Unity + iBatis + Asp.net Mvc 系统搭建
Unity + iBatis + Asp.net Mvc 系统搭建 之前用EntityFramework Code First做了一些小项目,很是方便:后来在一个 Java 项目中接触了myBatis ...
- html + CSS
Html 1 html基本标签 1.1 html文件结构 <!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN&qu ...
- 使用C#实现顺序队列
队列(Queue)是插入操作限定在表的尾部而其它操作限定在表的头部进行的线性表.把进行插入操作的表尾称为队尾(Rear),把进行其它操作的头部称为队头(Front).当对列中没有数据元素时称为空对列( ...
- js的逻辑 OR 运算符- ||
逻辑or运算大家都很熟悉,都会用.但是在javascript中用的更多,用的更妙.有时候用它来解决兼容问题特别方面.简洁. 比如获取鼠标对象.在 Internet Explorer 里, event ...
- 源码安装saltstack的时候遇到的问题
公司的系统都是内网,无法连接互联网,所以没办法只有源码安装了. 看了下saltstack的官网,需要安装的包有 https://docs.saltstack.com/en/latest/topics/ ...
- DeviceIOControl具体解释-各个击破
DeviceIoControl这个api我们用的不多,可是非常重要,有时会帮助我们实现一些特别的需求, 如获取硬件设备信息.与硬件设备通信(读写数据)等,对比msdn,以下我们详解一下这个api的使用 ...
- 了解你的家公家IP
我们总是在不在家的时候,须要訪问我们的电脑或设备,因为大多数人拥有来自ISP的动态IP,我们能够做一个小型设备来给我们的Android手机发送一个简单的通知,这样我们就能够总有IP用了,有 ...
- HDU2586
最近的共同祖先反复问的问题. #include <iostream> #include <algorithm> #include <vector> #include ...
- 【IOS】 遍历info 所有内容 && 唯一的节能设备UUID
/**获取装置imie*/ std::string DeviceInfo::getIMIE() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) NSStri ...
- POJ 3373 Changing Digits 好蛋疼的DP
一開始写的高位往低位递推,发现这样有些时候保证不了第四条要求.于是又開始写高位往低位的记忆化搜索,又发现传參什么的蛋疼的要死.然后又发现高位開始的记忆化搜索就是从低位往高位的递推呀,遂过之. dp[i ...