C# EPPlus 导出Excel
一、Excel导出帮助类 /*引用NuGet包 EPPlus*/
/*引用NuGet包 EPPlus*/
/// <summary>
/// Excel导出帮助类
/// </summary>
public class ExcelExportHelper
{
public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/// <summary>
/// List转DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = ; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = ; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
} /// <summary>
/// 导出Excel
/// </summary>
/// <param name="dataTable">数据源</param>
/// <param name="heading">工作簿Worksheet</param>
/// <param name="showSrNo">//是否显示行编号</param>
/// <param name="columnsToTake">要导出的列</param>
/// <returns></returns>
public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
{
byte[] result;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add($"{heading}Data");
int startRowFrom = string.IsNullOrEmpty(heading) ? : ; //开始的行
//是否显示行编号
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
dataColumn.SetOrdinal();
int index = ;
foreach (DataRow item in dataTable.Rows)
{
item[] = index;
index++;
}
}
//Add Content Into the Excel File
workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
// autofit width of cells with small content
int columnIndex = ;
foreach (DataColumn item in dataTable.Columns)
{
if (item.DataType == typeof(DateTime))
{
var i = dataTable.Columns.IndexOf(item);
//设置列格式为自定义 "yyyy/MM/dd HH:mm:ss"
workSheet.Cells[, i + , dataTable.Rows.Count + , i + ].Style.Numberformat.Format = "yyyy/MM/dd HH:mm";
}
ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
int maxLength = columnCells.Max(cell => cell.Value == null || cell.Value is DBNull || string.IsNullOrEmpty(cell.Value.ToString()) ? : cell.Value.ToString().Count());
if (maxLength < )
{
workSheet.Column(columnIndex).AutoFit();
}
columnIndex++;
}
// format header - bold, yellow on black
using (ExcelRange r = workSheet.Cells[startRowFrom, , startRowFrom, dataTable.Columns.Count])
{
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType = ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
}
// format cells - add borders
using (ExcelRange r = workSheet.Cells[startRowFrom + , , startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
// removed ignored columns
for (int i = dataTable.Columns.Count - ; i >= ; i--)
{
if (i == && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + );
}
}
if (!string.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
workSheet.Cells["A1"].Style.Font.Size = ;
workSheet.InsertColumn(, );
workSheet.InsertRow(, );
workSheet.Column().Width = ;
}
result = package.GetAsByteArray();
}
return result;
}
/// <summary>
/// 导出Excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="heading"></param>
/// <param name="isShowSlNo"></param>
/// <param name="columnsToTake"></param>
/// <returns></returns>
public static byte[] ExportExcel<T>(List<T> data, string heading = "", bool isShowSlNo = false, params string[] columnsToTake)
{
return ExportExcel(ListToDataTable(data), heading, isShowSlNo, columnsToTake);
}
}
二、调用
执行后Excel将会保存到D盘
string strSql = string.Format(@"SELECT TOP 10 [Name] AS 姓名,[PhoneNumber] AS 手机,[Email] AS 邮箱,[Department] AS 部门 FROM [User]");
DataTable dt = DBHelper.ExecuteTable(strSql);
string[] columns = { "姓名", "手机", "邮箱", "部门" };
byte[] filecontent = ExcelExportHelper.ExportExcel(dt, "", false, columns);
FileStream fs = new FileStream(@"D:\信息.xlsx", FileMode.Create, FileAccess.Write);
fs.Write(filecontent, , filecontent.Length);
fs.Flush();
fs.Close();
C# EPPlus 导出Excel的更多相关文章
- C# NPOI导出Excel和EPPlus导出Excel比较
系统中经常会使用导出Excel的功能. 之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到EPPlus可以用来导出Excel,就自己测了下两者导出上的差异. NPIO官网地址:http: ...
- C# NPOI导出Excel和EPPlus导出Excel
转自:http://www.cnblogs.com/tanpeng/p/6155749.html 系统中经常会使用导出Excel的功能.之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到 ...
- C# 使用Epplus导出Excel [5]:样式
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [4]:合并指定行
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [3]:合并列连续相同数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [2]:导出动态列数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [1]:导出固定列数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- asp.net下简单的Epplus导出excel
引用的命名空间 using System.IO; using OfficeOpenXml; /// <summary> /// 导出excel /// </summary> / ...
- C# EPPlus导出EXCEL,并生成Chart表
一 在negut添加EPPlus.dll库文件. 之前有写过直接只用Microsoft.Office.Interop.Excel 导出EXCEL,并生成Chart表,非常耗时,所以找了个EPPlus ...
随机推荐
- Windows 10系统快捷键
虚拟桌面 创建新的虚拟桌面:Win + Ctrl + D 关闭当前虚拟桌面:Win + Ctrl + F4 切换虚拟桌面:Win + Ctrl +左/右 任务视图:Win + Tab Win10常用W ...
- mysql 开启log-bin功能
今天搜索了一下增量备份脚本,简单查了一下,增量备份是通过mysql binlog来做的,就是将某段时间内的操作,保存到某二进制日志当中.备份就是备这个日志,恢复也是通过它.然鹅,这里我们需要先开启 ...
- 【转载】熟练利用google hacking来辅助我们快速渗透
转载于:https://klionsec.github.io/2014/12/14/search-hacking/?tdsourcetag=s_pcqq_aiomsg 0x01 google hack ...
- kubeadm 部署kubernetes1.14
节点信息: 主机名 IP 角色 k8s-master 10.10.0.10 master节点 k8s-node01 10.10.0.11 集群worke节点 k8s-node02 10.10.0.12 ...
- ThreadLocal的坑--ThreadLocal跨线程传递问题
1.父子线程间的传递问题 ThreadLocal的子类InheritableThreadLocal其实已经帮我们处理好了,通过这个组件可以实现父子线程之间的数据传递,在子线程中能够父线程中的Threa ...
- AtCoder整理(持续更新中……)
做了那么久的atcoder觉得自己的题解发的很乱 给有想和我一起交流atcoder题目(或者指出我做法的很菜)(或者指责我为什么整场比赛只会抄题解)的同学一个索引的机会??? 于是写了个爬虫爬了下 A ...
- S03_CH07_AXI_VDMA_OV5640摄像头采集系统
S03_CH07_AXI_VDMA_OV5640摄像头采集系统 7.1概述 本章内容和<S03_CH06_AXI_VDMA_OV7725摄像头采集系统>只是摄像头采用的分辨率不同,其他原理 ...
- css之word-wrap和word-break的区别
对于英文单词,如果有一个连写且长度很长的英文单词,在第一行显示不下的情况下,浏览器默认不会截断显示,而是把这个单词整体挪到下一行.但是当整体挪到下一行还是显示不完全该肿么办呢?有如下两个方法: wor ...
- Apache2.4+Tomcat7.0+php5.5整合配置详解
在上一篇的基础上,继续添加php的配置 一.首先下载php5.5 首先下载php5.5,到官网下载http://www.php.net/downloads.php,参考http://www.cnblo ...
- sonar+Jenkins 构建代码质量自动化分析平台
1.Sonar 介绍 Sonar 是一个用于管理代码质量的开源工具,可以分析代码中的bug和漏洞以及Code Smells,支持20多种编程语言的检测,如java,c/c++,python,php等语 ...