网上搜了下,很多代码都有各种问题,自己抽时间整理了一下这个导出
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Data;
using System.Reflection; namespace MySlSyj
{
public static class dataGridkz
{
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(); List<string> headers = new List<string>();
List<string> GetValue = new List<string>();
foreach (var cl in grid.Columns)
{
headers.Add(FormatCSVField(cl.Header.ToString())); } strBuilder
.Append(String.Join("", headers.ToArray()))
.Append("\t\n"); ////
//int i = 0;
string AA = "";
foreach (Object data in grid.ItemsSource)
{
var csvRow = new List<string>(); foreach (DataGridColumn col in grid.Columns)
{
string strValue = ""; Binding objBinding = null;
if (col is DataGridBoundColumn) objBinding = (col as DataGridBoundColumn).Binding; if (col is DataGridTemplateColumn)
{
//这是一个模板列
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();
}
} GetValue.Add(FormatCSVField(strValue));
} strBuilder.Append(String.Join("", GetValue.ToArray())).Append("\t\n");
GetValue.Clear();
} return strBuilder.ToString();
} private static string FormatCSVField(string data)
{ return String.Format("\t{0}", data.Replace("\"", "\t\n"));
} }
}