wpf 导出Excel
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 /// <summary> 9 /// CSV格式化 10 /// </summary> 11 /// <param name="data">数据</param> 12 /// <returns>格式化数据</returns> 13 private static string FormatCsvField(string data) 14 { 15 return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", "")); 16 } 17 18 19 20 /// <summary> 21 /// 导出DataGrid数据到Excel 22 /// </summary> 23 /// <param name="withHeaders">是否需要表头</param> 24 /// <param name="grid">DataGrid</param> 25 /// <param name="dataBind"></param> 26 /// <returns>Excel内容字符串</returns> 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 = new List<string>(); 35 List<string> bt = new List<string>(); 36 37 foreach (var hr in grid.Columns) 38 { 39 // DataGridTextColumn textcol = hr. as DataGridTextColumn; 40 headers.Add(hr.Header.ToString()); 41 if (hr is DataGridTextColumn)//列绑定数据 42 { 43 DataGridTextColumn textcol = hr as DataGridTextColumn; 44 if (textcol != 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 = new List<string>(); 62 foreach (var ab in bt) 63 { 64 string s = ReflectionUtil.GetProperty(data, ab).ToString(); 65 if (s != 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 = obj.GetType().GetProperty(propertyName); 90 if (info == null && propertyName.Split('.').Count() > 0) 91 { 92 object o = ReflectionUtil.GetProperty(obj, propertyName.Split('.')[0]); 93 int index = propertyName.IndexOf('.'); 94 string end = propertyName.Substring(index + 1, propertyName.Length - index - 1); 95 return ReflectionUtil.GetProperty(o, end); 96 } 97 object result = null; 98 try 99 { 100 result = info.GetValue(obj, null); 101 } 102 catch (TargetException) 103 { 104 return ""; 105 } 106 return result == null ? "" : result; 107 } 108 } 109 /// <summary> 110 /// 导出DataGrid数据到Excel为CVS文件 111 /// 使用utf8编码 中文是乱码 改用Unicode编码 112 /// 113 /// </summary> 114 /// <param name="withHeaders">是否带列头</param> 115 /// <param name="grid">DataGrid</param> 116 public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid) 117 { 118 try 119 { 120 string data = ExportDataGrid(true, grid, true); 121 var sfd = new Microsoft.Win32.SaveFileDialog 122 { 123 DefaultExt = "csv", 124 Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*", 125 FilterIndex = 1 126 }; 127 if (sfd.ShowDialog() == true) 128 { 129 using (Stream stream = sfd.OpenFile()) 130 { 131 using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode)) 132 { 133 data = data.Replace(",", "\t"); 134 writer.Write(data); 135 writer.Close(); 136 } 137 stream.Close(); 138 } 139 } 140 MessageBox.Show("导出成功!"); 141 } 142 catch (Exception ex) 143 { 144 // LogHelper.Error(ex); 145 } 146 } 147 148 #endregion 导出DataGrid数据到Excel 149 150
找了好多都有问题,这个可以分享给到家
转自:https://www.cnblogs.com/kmust/p/4412228.html