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 ...
随机推荐
- Java程序的编写与执行、Java新手常见问题及解决方法|乐字节Java学习
今天,我们来写一段Java程序.然后看看Java程序是如何执行的,以及Java新手小白遇到的问题和解决办法. 一.HelloWorld的编写 ① 新建一个XXX.java (文件的扩展名显示出来) ...
- [转帖]Pivotal Greenplum 6.0 新特性介绍
Pivotal Greenplum 6.0 新特性介绍 https://cloud.tencent.com/developer/news/391063 原来 greenplum 也是基于pg研发的. ...
- Linux/ubuntu 心得
基本命令 有n个软件未被升级(有强迫症的,不爽的 apt-get dist-upgrade 更改主机名字 git 不要免密输入的话,可在当前工作目录执行 git config credential.h ...
- docker 实践三:操作容器
在学习了 docker 镜像的内容后,我们在来看 docker 的另一个核心点:容器. 注:环境为 CentOS7,docker 19.03 docker 的容器是镜像的一个运行实例.docker 镜 ...
- S03_CH12_基于UDP的QSPI Flash bin文件网络烧写
S03_CH12_基于UDP的QSPI Flash bin文件网络烧写 12.1概述 为了满足不同的需求,本例程在"基于TCP的QSPI Flash bin文件网络烧写"上进行修改 ...
- rman备份跳过read only数据文件,减少备份总量,加快备份时间
客户需求,RMAN备份时间过长,想缩短备份时间,优化备份. 客户基于表空间进行历史数据归档的方式,将历史的表空间进行read only,想让RMAN跳过只读表空间,减少RMAN备份的数据总量,从而缩短 ...
- Java内存模型(JMM)
JVM与线程(线程在JVM中) 1.JVM什么时候启动? 类被调用时启动,此时会启动JVM线程然后再是其他的线程(main) 2.JVM内存区域 除了程序计数器(PC)之外都有可能发生 ...
- Python笔记-备忘
一.向列表添加元素 x.append(y) #末尾添加一个元素 x.extend([y,z]) #末尾添加多个元素 x.insert(index,y) 二.向列表获取元素 x[index] 三.从列表 ...
- list通过lambda 表达式去重,筛选
List<User> distinctList = new ArrayList();User user1 = new User();user1.setId("111") ...
- nginx的so_keepalive和timeout相关小计
KeepAlive 这里的keepalive是TCP的探活机制: [root@ ~]# sysctl -a |grep tcp_keepalive net.ipv4.tcp_keepalive_tim ...