silverlight导出excel的另一种方式

说明:《出自博客园--往事如锋》这个方法是从网上找到的,但是原来的方法没有考虑到绑定的字段是“自定义类型属性的属性” 以及更深(我在说啥呢。。)。我动了一些手脚完善了一点。

备注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 = new List<string>();
                foreach (DataGridColumn col in grid.Columns)
                {
                    if (col 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, null).GetTrimString()));
                                break;
                            }
                            else
                            {
                                currentData = propInfo.GetValue(currentData, null);
                            }

                        }

                    }
                }
                strBuilder
                    .Append(String.Join("", csvRow.ToArray()))
                    .Append("\t\n");
            }


            return strBuilder.ToString();
        }


private static 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://xTechnet.cnblogs.com/

说明:一切为了方便查看资料。。。

posted @ 2013-03-02 01:03  银河系上的地球  阅读(226)  评论(0编辑  收藏  举报