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 ...
随机推荐
- idea多级目录与单级目录切换
- [转载]C# MemoryStream(内存流)
MemoryStream位于System.IO命名空间,为系统内存提供流式的读写操作.常作为其他流数据交换时的中间对象操作. 1.MemoryStream类封装一个字节数组,在构造实例时可以使用一个字 ...
- stub_status监控Nginx使用情况!
stub_status监控Nginx使用情况! 查看nginx安装的模块! # /usr/local/nginx/sbin/nginx -V nginx version: nginx/1.8.1 bu ...
- [转帖]Greenplum :基于 PostgreSQL 的分布式数据库内核揭秘 (上篇)
Greenplum :基于 PostgreSQL 的分布式数据库内核揭秘 (上篇) https://www.infoq.cn/article/3IJ7L8HVR2MXhqaqI2RA 学长的文章.. ...
- js — 数组Array
目录 1. isArray 2. 转换方法 3. 分割字符串 join 4. 栈方法 5. 队列方法 6. 重排序方法 7. 操作方法 8. 位置方法 - 索引 9. 迭代方法 数组 array 解释 ...
- 100天搞定机器学习|Day3多元线性回归
前情回顾 [第二天100天搞定机器学习|Day2简单线性回归分析][1],我们学习了简单线性回归分析,这个模型非常简单,很容易理解.实现方式是sklearn中的LinearRegression,我们也 ...
- go defer 语句会延迟函数的执行直到上层函数返回。
defer code... 可以理解为 执行完当前defer所在的方法代码后执行defer 中的代码 常用在释放资源 比如 关闭文件 为防止忘记编写关闭代码 可以先写好 defer 各种释放资源 ...
- 少儿编程Scratch第四讲:射击游戏的制作,克隆的奥秘
上周的宇宙大战射击游戏中,我们只完成了宇宙飞船发射子弹的部分.还未制作敌对方.这周制作了敌方-飞龙,飞龙随机在屏幕上方出现,如果被子弹打中,则得分,飞龙和子弹都消失. 敌方:飞龙:计分. 目的 目的: ...
- hdu 1698 线段数的区间更新 以及延迟更新
先说说区间更新和单点更新的区别 主要的区别是搜索的过程 前者需要确定一个区间 后者就是一个点就好了 贴上两者代码 void updata(int i)//单点更新 { int l=stu[i].l; ...
- 【爬虫集合】抖音API分析
1. 分析接口 Charles注册码 Registered Name: https://zhile.io License Key: 48891cf209c6d32bf4 抖音API分析 抖音.猫眼网页 ...