当前位置: 首页 > news >正文

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()即可

相关文章:

  • Android编程之如何取得View的当前位置
  • Android4.0内存Dex数据动态加载技术
  • C# 网络编程之网页自动登录 (一).使用WebBrower控件模仿登录
  • 文章收录1
  • windows服务器应对高并发和DDOS攻击
  • 公开课可下载资源汇总
  • 将solr3.5整合到Tomcat6.x中
  • 自己写Lucene分词器原理篇——ChineseAnalyzer简单讲解
  • 一个Java程序员应该掌握的10项技能
  • 自己写Lucene分词器示例篇——写一个简单点额分析器
  • java中的接口和抽象类是什么?
  • 并查集专题【完结】
  • Apache配置优化
  • hdu1010 Tempter of the Bone 成长---纠错
  • lucene 4.x中如何只存储不做索引
  • (十五)java多线程之并发集合ArrayBlockingQueue
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • 【剑指offer】让抽象问题具体化
  • 【面试系列】之二:关于js原型
  • Golang-长连接-状态推送
  • JavaScript中的对象个人分享
  • js正则,这点儿就够用了
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • SQLServer插入数据
  • Unix命令
  • Vue.js 移动端适配之 vw 解决方案
  • 安卓应用性能调试和优化经验分享
  • 半理解系列--Promise的进化史
  • -- 查询加强-- 使用如何where子句进行筛选,% _ like的使用
  • 道格拉斯-普克 抽稀算法 附javascript实现
  • 反思总结然后整装待发
  • 工作中总结前端开发流程--vue项目
  • 前端
  • 异常机制详解
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (附源码)springboot家庭财务分析系统 毕业设计641323
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • (十六)串口UART
  • (转)h264中avc和flv数据的解析
  • (转)程序员技术练级攻略
  • (转)四层和七层负载均衡的区别
  • (转载)(官方)UE4--图像编程----着色器开发
  • *++p:p先自+,然后*p,最终为3 ++*p:先*p,即arr[0]=1,然后再++,最终为2 *p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1]
  • 、写入Shellcode到注册表上线
  • .net core 源码_ASP.NET Core之Identity源码学习
  • .NET 简介:跨平台、开源、高性能的开发平台
  • .NET是什么
  • .net下简单快捷的数值高低位切换
  • @RequestBody与@ModelAttribute
  • @在php中起什么作用?
  • [2010-8-30]
  • [20190416]完善shared latch测试脚本2.txt
  • [Android]How to use FFmpeg to decode Android f...