1 private void Button_Click_1(object sender, RoutedEventArgs e)
2 {
3
4 ExportDataGridSaveAs(true, this.data);
5 }
6 #region wpf客户端 导出DataGrid数据到Excel
7
8 ///
9 /// CSV格式化
10 ///
11 /// 数据
12 ///
13 private static string FormatCsvField(string data)
14 {
15 return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
16 }
17
18
19
20 ///
21 /// 导出DataGrid数据到Excel
22 ///
23 /// 是否需要表头
24 /// DataGrid
25 ///
26 ///
27 public static string ExportDataGrid(bool withHeaders, System.Windows.Controls.DataGrid grid, bool dataBind)
28 {
29 try
30 {
31 var strBuilder = new System.Text.StringBuilder();
32 var source = (grid.ItemsSource as System.Collections.IList);
33 if (source == null) return "";
34 var headers &#61; new List<string>();
35 List<string> bt &#61; new List<string>();
36
37 foreach (var hr in grid.Columns)
38 {
39 // DataGridTextColumn textcol &#61; hr. as DataGridTextColumn;
40 headers.Add(hr.Header.ToString());
41 if (hr is DataGridTextColumn)//列绑定数据
42 {
43 DataGridTextColumn textcol &#61; hr as DataGridTextColumn;
44 if (textcol !&#61; null)
45 bt.Add((textcol.Binding as Binding).Path.Path.ToString()); //获取绑定源
46
47 }
48 else if (hr is DataGridTemplateColumn)
49 {
50 if (hr.Header.Equals("操作"))
51 bt.Add("Id");
52 }
53 else
54 {
55
56 }
57 }
58 strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
59 foreach (var data in source)
60 {
61 var csvRow &#61; new List<string>();
62 foreach (var ab in bt)
63 {
64 string s &#61; ReflectionUtil.GetProperty(data, ab).ToString();
65 if (s !&#61; null)
66 {
67 csvRow.Add(FormatCsvField(s));
68 }
69 else
70 {
71 csvRow.Add("\t");
72 }
73 }
74 strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
75 // strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
76 }
77 return strBuilder.ToString();
78 }
79 catch (Exception ex)
80 {
81 // LogHelper.Error(ex);
82 return "";
83 }
84 }
85 public class ReflectionUtil
86 {
87 public static object GetProperty(object obj, string propertyName)
88 {
89 PropertyInfo info &#61; obj.GetType().GetProperty(propertyName);
90 if (info &#61;&#61; null && propertyName.Split(&#39;.&#39;).Count() > 0)
91 {
92 object o &#61; ReflectionUtil.GetProperty(obj, propertyName.Split(&#39;.&#39;)[0]);
93 int index &#61; propertyName.IndexOf(&#39;.&#39;);
94 string end &#61; propertyName.Substring(index &#43; 1, propertyName.Length - index - 1);
95 return ReflectionUtil.GetProperty(o, end);
96 }
97 object result &#61; null;
98 try
99 {
100 result &#61; info.GetValue(obj, null);
101 }
102 catch (TargetException)
103 {
104 return "";
105 }
106 return result &#61;&#61; null ? "" : result;
107 }
108 }
109 ///
110 /// 导出DataGrid数据到Excel为CVS文件
111 /// 使用utf8编码 中文是乱码 改用Unicode编码
112 ///
113 ///
114 /// 是否带列头
115 /// DataGrid
116 public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid)
117 {
118 try
119 {
120 string data &#61; ExportDataGrid(true, grid, true);
121 var sfd &#61; new Microsoft.Win32.SaveFileDialog
122 {
123 DefaultExt &#61; "csv",
124 Filter &#61; "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
125 FilterIndex &#61; 1
126 };
127 if (sfd.ShowDialog() &#61;&#61; true)
128 {
129 using (Stream stream &#61; sfd.OpenFile())
130 {
131 using (var writer &#61; new StreamWriter(stream, System.Text.Encoding.Unicode))
132 {
133 data &#61; data.Replace(",", "\t");
134 writer.Write(data);
135 writer.Close();
136 }
137 stream.Close();
138 }
139 }
140 MessageBox.Show("导出成功&#xff01;");
141 }
142 catch (Exception ex)
143 {
144 // LogHelper.Error(ex);
145 }
146 }
147
148 #endregion 导出DataGrid数据到Excel
149
150
找了好多都有问题&#xff0c;这个可以分享给到家
转自&#xff1a;https://www.cnblogs.com/kmust/p/4412228.html