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 ...
随机推荐
- JavaScript中的Truthy和Falsy
JavaScript中存在Truthy值和Falsy值的概念 — 除了boolean值true.false外,所有类型的JavaScript值均可用于逻辑判断,其规则如下: 1.所有的Falsy值,当 ...
- python argparse库
argparse用法总结 https://blog.csdn.net/qq_24551305/article/details/90155858 args = parse.parse_args()par ...
- nginx check健康检查
nginx利用第三方模块nginx_upstream_check_module来检查后端服务器的健康情况 大家都知道,前段nginx做反代,如果后端服务器宕掉的话,nginx是不能把这台realser ...
- K8S从入门到放弃系列-(12)Kubernetes集群Coredns部署
摘要: 集群其他组件全部完成后我们应当部署集群 DNS 使 service 等能够正常解析,1.11版本coredns已经取代kube-dns成为集群默认dns. 1)下载yaml配置清单 [root ...
- java输入输出 -- Java NIO之选择器
一.简介 前面的文章说了缓冲区,说了通道,本文就来说说 NIO 中另一个重要的实现,即选择器 Selector.在更早的文章中,我简述了几种 IO 模型.如果大家看过之前的文章,并动手写过代码的话.再 ...
- 100天搞定机器学习|Day4-6 逻辑回归
逻辑回归avik-jain介绍的不是特别详细,下面再唠叨一遍这个算法. 1.模型 在分类问题中,比如判断邮件是否为垃圾邮件,判断肿瘤是否为阳性,目标变量是离散的,只有两种取值,通常会编码为0和1.假设 ...
- Django Simple Captcha的使用
Django Simple Captcha的使用 1.下载Django Simple Captcha django-simple-captcha官方文档地址 http://django-simple- ...
- ARM协处理器CP15寄存器详解
改自:https://blog.csdn.net/gameit/article/details/13169405 *C2描述的不对,bit[31-14]才是TTB,不是所有的bit去存储ttb.很明显 ...
- Nginx学习笔记(一):Nginx 进程模型 / 事件处理模型
Nginx 进程模型 多进程模型 进程间相互独立,无需加锁,且互不影响: 一个进程退出了不影响其他的进程运行,降低风险: 当请求到来,多个 worker 通过竞争 accrpt_mutex ...
- 游记-pkupc&cts2019
Day0 和boshi.Rayment组的队,昨天听学长说这次比赛可以加学分,他们信科的大部分人都会参加,估摸有两百多支队伍--然而奖品只有不到一百份 我要奖品呐! 上午十一点半到的北京,拉着行李提着 ...