wpf 导出Excel
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的更多相关文章
- WPF 导出Excel(合并单元格)
WPF 导出Excel(合并单元格) DataTable 导出Excel(导出想要的列,不想要的去掉) ,B1,B2,B3,B4,B5} MisroSoft.Office.Interop.Excel. ...
- wpf 导出Excel Wpf Button 样式 wpf简单进度条 List泛型集合对象排序 C#集合
wpf 导出Excel 1 private void Button_Click_1(object sender, RoutedEventArgs e) 2 { 3 4 ExportDataGrid ...
- WPF 导出Excel 导出图片
/// <summary> /// 导出Excel /// </summary> private void ExportExcel(DataTable ExcelDt) { / ...
- C#使用Aspose.Cells导出Excel简单实现
首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...
- 利用poi导出Excel
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...
- [django]数据导出excel升级强化版(很强大!)
不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...
- NPOI导出Excel
using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- asp.net DataTable导出Excel 自定义列名
1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...
随机推荐
- [AI]神经网络章3 损失函数
损失函数 作用 在有监督的学习中,需要衡量神经网络输出和所预期的输出之间的差异大小.这种误差函数需要能够反映出当前网络输出和实际结果之间一种量化之后的不一致程度,也就是说函数值越大,反映出模型预测的结 ...
- js模态框实现原理
<!DOCTYPE> <html> <head> <style>/* 定义模态对话框外面的覆盖层样式 */ #modal-overlay { visib ...
- inet_pton和inet_ntop inet_ntoa
Linux下地址转换函数 inet_pton ==> Ox inet_ntop ==> xxx.xxx.xxx #include <sys/types.h> #include ...
- python学习 day1 (3月1日)
01 cpu 内存 硬盘 操作系统 CPU:中央处理器,相当于人大脑. 飞机 内存:临时存储数据. 8g,16g, 高铁 1,成本高. 2,断电即消失. 硬盘:长期存储大量的数据. 1T 512G等等 ...
- 再读c++primer plus 006
使用类: 1.重载限制:(1)重载后的运算符必须至少有一个操作数是用户定义的类型,这将防止用户为标准类型重载运算符 (2)使用运算符时不能违反运算符原来的语法规则,不能修改运算符的优先级 (3)不能创 ...
- Educational Codeforces Round 61 D 二分 + 线段树
https://codeforces.com/contest/1132/problem/D 二分 + 线段树(弃用结构体型线段树) 题意 有n台电脑,只有一个充电器,每台电脑一开始有a[i]电量,每秒 ...
- 5W2H+35问
之前看到的一个非常好且全面的做事方法论.
- poj 2506 Tiling(高精度)
Description In how many ways can you tile a 2xn rectangle by 2x1 or 2x2 tiles? Here is a sample tili ...
- #微码分享#AES算法的C++包装类
AES为Advanced Encryption Standard的缩写,中文名:高级加密标准,在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准,用来替代DES.基于std:: ...
- Linux批量远程命令和上传下载工具
https://github.com/eyjian/mooon/releases/tag/mooon-tools mooon_ssh:批量远程命令工具,在多台机器上执行指定命令 mooon_uploa ...