private void Button_Click_1(object sender, RoutedEventArgs e)
{ ExportDataGridSaveAs(true, this.data);
}
#region wpf客户端 导出DataGrid数据到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>
/// <param name="dataBind"></param>
/// <returns>Excel内容字符串</returns>
public static string ExportDataGrid(bool withHeaders, System.Windows.Controls.DataGrid grid, bool dataBind)
{
try
{
var strBuilder = new System.Text.StringBuilder();
var source = (grid.ItemsSource as System.Collections.IList);
if (source == null) return "";
var headers = new List<string>();
List<string> bt = new List<string>(); foreach (var hr in grid.Columns)
{
// DataGridTextColumn textcol = hr. as DataGridTextColumn;
headers.Add(hr.Header.ToString());
if (hr is DataGridTextColumn)//列绑定数据
{
DataGridTextColumn textcol = hr as DataGridTextColumn;
if (textcol != null)
bt.Add((textcol.Binding as Binding).Path.Path.ToString()); //获取绑定源 }
else if (hr is DataGridTemplateColumn)
{
if (hr.Header.Equals("操作"))
bt.Add("Id");
}
else
{ }
}
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (var data in source)
{
var csvRow = new List<string>();
foreach (var ab in bt)
{
string s = ReflectionUtil.GetProperty(data, ab).ToString();
if (s != null)
{
csvRow.Add(FormatCsvField(s));
}
else
{
csvRow.Add("\t");
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
// strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
}
return strBuilder.ToString();
}
catch (Exception ex)
{
// LogHelper.Error(ex);
return "";
}
}
public class ReflectionUtil
{
public static object GetProperty(object obj, string propertyName)
{
PropertyInfo info = obj.GetType().GetProperty(propertyName);
if (info == null && propertyName.Split('.').Count() > )
{
object o = ReflectionUtil.GetProperty(obj, propertyName.Split('.')[]);
int index = propertyName.IndexOf('.');
string end = propertyName.Substring(index + , propertyName.Length - index - );
return ReflectionUtil.GetProperty(o, end);
}
object result = null;
try
{
result = info.GetValue(obj, null);
}
catch (TargetException)
{
return "";
}
return result == null ? "" : result;
}
}
/// <summary>
/// 导出DataGrid数据到Excel为CVS文件
/// 使用utf8编码 中文是乱码 改用Unicode编码
///
/// </summary>
/// <param name="withHeaders">是否带列头</param>
/// <param name="grid">DataGrid</param>
public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid)
{
try
{
string data = ExportDataGrid(true, grid, true);
var sfd = new Microsoft.Win32.SaveFileDialog
{
DefaultExt = "csv",
Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
FilterIndex =
};
if (sfd.ShowDialog() == true)
{
using (Stream stream = sfd.OpenFile())
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
{
data = data.Replace(",", "\t");
writer.Write(data);
writer.Close();
}
stream.Close();
}
}
MessageBox.Show("导出成功!");
}
catch (Exception ex)
{
// LogHelper.Error(ex);
}
} #endregion 导出DataGrid数据到Excel

找了好多都有问题,这个可以分享给到家

转自:https://www.cnblogs.com/kmust/p/4412228.html

wpf 导出Excel的更多相关文章

  1. WPF 导出Excel(合并单元格)

    WPF 导出Excel(合并单元格) DataTable 导出Excel(导出想要的列,不想要的去掉) ,B1,B2,B3,B4,B5} MisroSoft.Office.Interop.Excel. ...

  2. wpf 导出Excel Wpf Button 样式 wpf简单进度条 List泛型集合对象排序 C#集合

    wpf 导出Excel   1 private void Button_Click_1(object sender, RoutedEventArgs e) 2 { 3 4 ExportDataGrid ...

  3. WPF 导出Excel 导出图片

    /// <summary> /// 导出Excel /// </summary> private void ExportExcel(DataTable ExcelDt) { / ...

  4. C#使用Aspose.Cells导出Excel简单实现

    首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...

  5. 利用poi导出Excel

    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...

  6. [django]数据导出excel升级强化版(很强大!)

    不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...

  7. NPOI导出Excel

    using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...

  8. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  9. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

随机推荐

  1. 微信小程序获取当前位置

    详细参数说明请看小程序api文档:https://developers.weixin.qq.com/miniprogram/dev/api/wx.openLocation.html wx.getLoc ...

  2. kbmMW均衡负载与容灾(2)(转载红鱼儿)

    集中式均衡负载 为实现集中式均衡负载方案,需要实现两个不同的应用服务器,一个是只包含均衡负载组件再无其他内容的应用服务器,可称之为均衡负载应用服务器,下文简称LB Server,另外一个就是包含一个或 ...

  3. 【转】mysql查看表空间占用情况

    ${database} 为数据库的名称 /*1.查看索引 (1)单位是GB*/ SELECT CONCAT(ROUND(SUM(index_length)/(**), ), ' GB') AS 'To ...

  4. 2018.12.15 spoj Substrings(后缀自动机)

    传送门 后缀自动机基础题. 求长度为iii的子串出现次数的最大值. 对原串建出samsamsam,然后用sizsizsiz更新每个maxlenmaxlenmaxlen的答案. 然后由于后缀链接将其转化 ...

  5. boost-容器

    1.array array相当于是一个增加了STL容器接口的数组,但它不像vector等容器一样可以动态增长,如果需要动态变动array的容量可以使用boost::scoped_array.array ...

  6. openstack之虚拟机管理命令

    在控制节点上建hzb-openrc.sh export OS_PROJECT_DOMAIN_ID=default export OS_USER_DOMAIN_ID=default export OS_ ...

  7. 学以致用十一-----centos7.2+python3+YouCompleteMe走过的坑

    目的,安装YouCompleteMe 插件 参考的资料 https://blog.csdn.net/zs376957686/article/details/77833953 https://www.c ...

  8. Atcoder Grand-014 Writeup

    A - Cookie Exchanges 题面 Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respec ...

  9. (转)mysql command line client打不开(闪一下消失)的解决办法

    转自:http://www.2cto.com/database/201209/153858.html 网上搜索到的解决办法: 1.找到mysql安装目录下的bin目录路径. 2.打开cmd,进入到bi ...

  10. thrift使用总结

    转自 http://blog.csdn.net/qq_27784479/article/details/73250958 Apache Thrift软件框架用于可扩展的跨语言服务开发,简单来说就是RP ...