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. Subarray Sum Equals K LT560

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  2. 利用PHP脚本辅助MySQL数据库管理5-检查异常数据

    <?php $dbi = new DbMysql; $dbi->dbh = 'mysql://root:mysql@127.0.0.1/coffeetest'; $map = array( ...

  3. ECLIPSE使用HG插件去上载 GOOGLE.CODE下的代码

    ECLIPSE使用HG插件去上载 GOOGLE.CODE下的代码 www.MyException.Cn   发布于:2012-09-10 22:20:12   浏览:112次 0   ECLIPSE使 ...

  4. 非接触IC卡中typeA卡和typeB卡的区别--总结,二者的调制方式和编码方式不同

    非接触IC卡中typeA卡和typeB卡的区别--总结,二者的调制方式和编码方式不同 1.非接触式IC卡的国际规范ISO/IEC14443的由来? 在非接触式IC卡的发展过程中,这些问题逐渐被解决并形 ...

  5. 2018.12.22 spoj7258 Lexicographical Substring Search(后缀自动机)

    传送门 samsamsam基础题. 题意简述:给出一个串,询问第kkk大的本质不同的串. 然而这就是弦论的简化版. 我们把samsamsam建出来然后贪心选择就行了. 代码: #include< ...

  6. Methods to reduce the number of pipeline stages

    Several techniques have been proposed to reduce the number of pipeline stages. We categorize them in ...

  7. linux命令tee用法

    功能说明:读取标准输入的数据,并将其内容输出成文件. 语 法:tee [-ai][--help][--version][文件…] 补充说明:tee指令会从标准输入设备读取数据,将其内容输出到标准输出设 ...

  8. PYTHON编码处理-str与Unicode的区别

    一篇关于STR和UNICODE的好文章 整理下python编码相关的内容 注意: 以下讨论为Python2.x版本, Py3k的待尝试 开始 用python处理中文时,读取文件或消息,http参数等等 ...

  9. [待完善]mycat使用(一)

    生产上的mycat已经投入使用,这次的应用场景是数据写入和查询都非常大的一个需求,而且经常出现多表join的查询 1.应用上线没多久出现大量慢查询: 分片键的选择率非常高,但没有建索引,在其上加上索引 ...

  10. Json跨域请求数-Jquery Ajax请求

    同步请求,async(是否异步) //同步请求,等待并接收返回的结果 var result = $.ajax({ type: "GET", url: address, async: ...