zlb

silverlight3datagrid中的数据导出到excel

datagrid中的数据导出到excel
转换成csv格式的数据 用excel打开

  /// <summary>
        
/// CSV格式化
        
/// </summary>
        
/// <param name="data">数据</param>
        
/// <returns>格式化数据</returns>
        private static string FormatCSVField(string data)
        {
            
return String.Format("\"{0}\"", data.Replace("\"""\"\"\"").Replace("\n""").Replace("\r"""));
        }

        
/// <summary>
        
/// 导出DataGrid数据到Excel
        
/// </summary>
        
/// <param name="withHeaders">是否需要表头</param>
        
/// <param name="grid">DataGrid</param>
        
/// <returns>Excel内容字符串</returns>
        public static string ExportDataGrid(bool withHeaders, DataGrid grid)
        {
            
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 == nullreturn "";
            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("\r\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;
                        propInfo 
= data.GetType().GetProperty(colPath);
                        
if (propInfo != null)
                        {
                            csvRow.Add(FormatCSVField(propInfo.GetValue(data, 
null).ToString()));
                        }
                    }
                }
                strBuilder.Append(String.Join(
",", csvRow.ToArray())).Append("\r\n");
            }
            
return strBuilder.ToString();
        }
        
/// <summary>
        
/// 导出DataGrid数据到Excel
        
/// </summary>
        
/// <param name="withHeaders">是否需要表头</param>
        
/// <param name="grid">DataGrid</param>
        
/// <returns>Excel内容字符串</returns>
        public static string ExportDataGrid(bool withHeaders, DataGrid grid,bool dataBind)
        {
            
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 == nullreturn "";
            List
<string> headers = new List<string>();
            grid.Columns.ToList().ForEach(col 
=>
            {
                
if (col is DataGridTemplateColumn)
                {
                    
if (col.Header!=null)
                    {
                        headers.Add(FormatCSVField(col.Header.ToString()));
                    }
                    
else
                    {
                        headers.Add(
string.Empty);
                    }
                }
            });
            strBuilder.Append(String.Join(
",", headers.ToArray())).Append("\r\n");
            
foreach (Object data in source)
            {
                List
<string> csvRow = new List<string>();
                
foreach (DataGridColumn col in grid.Columns)
                {
                    
if (col is DataGridTemplateColumn)
                    {
                        FrameworkElement cellContent 
= col.GetCellContent(data);
                        TextBlock block 
= cellContent as TextBlock;
                        
if (block != null)
                        {
                            csvRow.Add(FormatCSVField(block.Text));
                        }
                    }
                }
                strBuilder.Append(String.Join(
",", csvRow.ToArray())).Append("\r\n");
            }
            
return strBuilder.ToString();
调用上面的方法

  void btnExport_Click(object sender, RoutedEventArgs e)
         {
             
string data = AppCode.Common.ExportDataGrid(truethis.dg,true);
             SaveFileDialog sfd 
= new SaveFileDialog();
             sfd.DefaultExt 
= "csv";
             sfd.Filter 
= "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";
         
             sfd.FilterIndex
=1;

             
if (sfd.ShowDialog() == true)
             {
                  
using (Stream stream = sfd.OpenFile())
                  {
//用utf8编码
                         Byte[] fileContent = System.Text.UTF8Encoding.UTF8.GetBytes(data);
                         stream.Write(fileContent, 
0, fileContent.Length);
                         stream.Close();
                   }              
             }

用此方法生成的文件在我的电脑环境office2007 win2003下打开是乱码
但是在同事的机子上打开都正常(xp office2007)

posted on 2009-09-11 19:02  zlb  阅读(505)  评论(0编辑  收藏  举报

导航