前言

  导出数据在管理系统中经常要用到,目前的Excel导出工具多种多样,如:NPOI、EPPlus等……本篇使用的是EPPlus,记录下在工作中用到的导入导出类,以便后面使用

代码

  导出

public class Export2Excel
{
/// <summary>
/// 生成excel
/// </summary>
/// <param name="dtSource">数据源</param>
/// <param name="title">标题(Sheet名)</param>
/// <param name="showTitle">是否显示</param>
/// <returns></returns>
public static MemoryStream Export(DataTable dtSource, string title, bool showTitle = true)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(title); int maxColumnCount = dtSource.Columns.Count;
int curRowIndex = 0; if (showTitle == true)
{
curRowIndex++;
//主题
workSheet.Cells[curRowIndex, 1, 1, maxColumnCount].Merge = true;
workSheet.Cells[curRowIndex, 1].Value = title;
var headerStyle = workSheet.Workbook.Styles.CreateNamedStyle("headerStyle");
headerStyle.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
headerStyle.Style.Font.Bold = true;
headerStyle.Style.Font.Size = 20;
workSheet.Cells[curRowIndex, 1].StyleName = "headerStyle"; curRowIndex++;
//导出时间栏
workSheet.Cells[curRowIndex, 1, 2, maxColumnCount].Merge = true;
workSheet.Cells[curRowIndex, 1].Value = "导出时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
workSheet.Cells[curRowIndex, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
} curRowIndex++;
var titleStyle = workSheet.Workbook.Styles.CreateNamedStyle("titleStyle");
titleStyle.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
titleStyle.Style.Font.Bold = true;
//标题
for (var i = 0; i < maxColumnCount; i++)
{
DataColumn column = dtSource.Columns[i];
workSheet.Cells[curRowIndex, i + 1].Value = column.ColumnName;
workSheet.Cells[curRowIndex, i + 1].StyleName = "titleStyle";
}
workSheet.View.FreezePanes(curRowIndex, 1);//冻结标题行 //内容
for (var i = 0; i < dtSource.Rows.Count; i++)
{
curRowIndex++;
for (var j = 0; j < maxColumnCount; j++)
{
DataColumn column = dtSource.Columns[j];
var row = dtSource.Rows[i];
object value = row[column];
var cell = workSheet.Cells[curRowIndex, j + 1];
var pType = column.DataType;
pType = pType.Name == "Nullable`1" ? Nullable.GetUnderlyingType(pType) : pType;
if (pType == typeof(DateTime))
{
cell.Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
cell.Value = Convert.ToDateTime(value);
}
else if (pType == typeof(int))
{
cell.Value = Convert.ToInt32(value);
}
else if (pType == typeof(double) || pType == typeof(decimal))
{
cell.Value = Convert.ToDouble(value);
}
else
{
cell.Value = value == null ? "" : value.ToString();
}
workSheet.Cells[curRowIndex, j + 1].Value = row[column].ToString();
}
}
workSheet.Cells[workSheet.Dimension.Address].Style.Font.Name = "宋体";
workSheet.Cells[workSheet.Dimension.Address].AutoFitColumns();//自动填充
for (var i = 1; i <= workSheet.Dimension.End.Column; i++) { workSheet.Column(i).Width = workSheet.Column(i).Width + 2; }//在填充的基础上再加2
MemoryStream ms = new MemoryStream(package.GetAsByteArray());
return ms;
}
} /// <summary>
/// 生成excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dtSource">数据源</param>
/// <param name="columns">导出字段表头合集</param>
/// <param name="title">标题(Sheet名)</param>
/// <param name="showTitle">是否显示标题</param>
/// <returns></returns>
public static byte[] Export<T>(IList<T> dtSource, ExportColumnCollective columns, string title, bool showTitle = true)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(title); int maxColumnCount = columns.ExportColumnList.Count;
int curRowIndex = 0; //Excel标题
if (showTitle == true)
{
curRowIndex++;
workSheet.Cells[curRowIndex, 1, 1, maxColumnCount].Merge = true;
workSheet.Cells[curRowIndex, 1].Value = title;
var headerStyle = workSheet.Workbook.Styles.CreateNamedStyle("headerStyle");
headerStyle.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
headerStyle.Style.Font.Bold = true;
headerStyle.Style.Font.Size = 20;
workSheet.Cells[curRowIndex, 1].StyleName = "headerStyle"; curRowIndex++;
//导出时间
workSheet.Cells[curRowIndex, 1, 2, maxColumnCount].Merge = true;
workSheet.Cells[curRowIndex, 1].Value = "导出时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
workSheet.Cells[curRowIndex, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
} //数据表格标题(列名)
for (int i = 0, rowCount = columns.HeaderExportColumnList.Count; i < rowCount; i++)
{
curRowIndex++;
workSheet.Cells[curRowIndex, 1, curRowIndex, maxColumnCount].Style.Font.Bold = true;
var curColSpan = 1;
for (int j = 0, colCount = columns.HeaderExportColumnList[i].Count; j < colCount; j++)
{
var colColumn = columns.HeaderExportColumnList[i][j];
var colSpan = FindSpaceCol(workSheet, curRowIndex, curColSpan);
if (j == 0) curColSpan = colSpan;
var toColSpan = colSpan + colColumn.ColSpan;
var cell = workSheet.Cells[curRowIndex, colSpan, colColumn.RowSpan + curRowIndex, toColSpan];
cell.Merge = true;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
workSheet.Cells[curRowIndex, colSpan].Value = colColumn.Title;
curColSpan += colColumn.ColSpan;
}
}
workSheet.View.FreezePanes(curRowIndex + 1, 1);//冻结标题行 Type type = typeof(T);
PropertyInfo[] propertyInfos = type.GetProperties();
if (propertyInfos.Count() == 0 && dtSource.Count > 0) propertyInfos = dtSource[0].GetType().GetProperties(); //数据行
for (int i = 0, sourceCount = dtSource.Count(); i < sourceCount; i++)
{
curRowIndex++;
for (var j = 0; j < maxColumnCount; j++)
{
var column = columns.ExportColumnList[j];
var cell = workSheet.Cells[curRowIndex, j + 1];
foreach (var propertyInfo in propertyInfos)
{
if (column.Field == propertyInfo.Name)
{
object value = propertyInfo.GetValue(dtSource[i]);
var pType = propertyInfo.PropertyType;
pType = pType.Name == "Nullable`1" ? Nullable.GetUnderlyingType(pType) : pType;
if (pType == typeof(DateTime))
{
cell.Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
cell.Value = Convert.ToDateTime(value);
}
else if (pType == typeof(int))
{
cell.Style.Numberformat.Format = "#0";
cell.Value = Convert.ToInt32(value);
}
else if (pType == typeof(double) || pType == typeof(decimal))
{
if (column.Precision != null) cell.Style.Numberformat.Format = "#,##0.00";//保留两位小数 cell.Value = Convert.ToDouble(value);
}
else
{
cell.Value = value == null ? "" : value.ToString();
}
}
}
}
}
workSheet.Cells[workSheet.Dimension.Address].Style.Font.Name = "宋体";
workSheet.Cells[workSheet.Dimension.Address].AutoFitColumns();//自动填充
for (var i = 1; i <= workSheet.Dimension.End.Column; i++) { workSheet.Column(i).Width = workSheet.Column(i).Width + 2; }//在填充的基础上再加2 return package.GetAsByteArray();
}
} private static int FindSpaceCol(ExcelWorksheet workSheet, int row, int col)
{
if (workSheet.Cells[row, col].Merge)
{
return FindSpaceCol(workSheet, row, col + 1);
}
return col;
}
}
public class ExportColumnCollective
{
/// <summary>
/// 字段列集合
/// </summary>
public List<ExportColumn> ExportColumnList { get; set; }
/// <summary>
/// 表头或多表头集合
/// </summary>
public List<List<ExportColumn>> HeaderExportColumnList { get; set; }
}
public class ExportColumn
{ /// <summary>
/// 标题
/// </summary>
[JsonProperty("title")]
public string Title { get; set; }
/// <summary>
/// 字段
/// </summary>
[JsonProperty("field")]
public string Field { get; set; }
/// <summary>
/// 精度(只对double、decimal有效)
/// </summary>
[JsonProperty("precision")]
public int? Precision { get; set; }
/// <summary>
/// 跨列
/// </summary>
[JsonProperty("colSpan")]
public int ColSpan { get; set; }
/// <summary>
/// 跨行
/// </summary>
[JsonProperty("rowSpan")]
public int RowSpan { get; set; }
}

  导入

public class Import2Excel<T> where T : XlsRow, new()
{
private List<XlsEntity> xlsHeader = new List<XlsEntity>(); #region 初始化转换形式
public void ForMember(Expression<Func<T, object>> entityExpression, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsEntity.ColumnName = xlsEntity.EntityName;
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
}
public void ForMember(string columnName, Expression<Func<T, object>> entityExpression)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsHeader.Add(xlsEntity);
}
public void ForMember(string columnName, string entityName)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = entityName;
xlsHeader.Add(xlsEntity);
}
public void ForMember(string columnName, string entityName, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = entityName;
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
}
public void ForMember(string columnName, Expression<Func<T, object>> entityExpression, Func<string, object> func)
{
XlsEntity xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = GetPropertyName(entityExpression);
xlsEntity.ConvertFunc = func;
xlsHeader.Add(xlsEntity);
}
#endregion /// <summary>
/// Excel文件流加载到内存
/// </summary>
/// <param name="ExcelFileStream">文件流</param>
/// <param name="SheetIndex">加载页码</param>
/// <returns></returns>
public List<T> LoadFromExcel(Stream ExcelFileStream, int SheetIndex = 0)
{
List<T> resultList = new List<T>(); using (ExcelPackage package = new ExcelPackage(ExcelFileStream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[SheetIndex];//选定 指定页 int colStart = worksheet.Dimension.Start.Column;
int colEnd = worksheet.Dimension.End.Column;
int rowStart = worksheet.Dimension.Start.Row;
int rowEnd = worksheet.Dimension.End.Row; PropertyInfo[] propertyInfoList = typeof(T).GetProperties();
XlsEntity xlsEntity; #region 将实体和excel列标题进行对应绑定,添加到集合中 for (int i = colStart; i <= colEnd; i++)
{
string columnName = worksheet.Cells[rowStart, i].Value.ToString(); xlsEntity = xlsHeader.FirstOrDefault(e => e.ColumnName == columnName); for (int j = 0; j < propertyInfoList.Length; j++)
{
if (xlsEntity != null && xlsEntity.ColumnName == columnName)
{
xlsEntity.ColumnIndex = i;
xlsHeader.Add(xlsEntity);
}
else if (propertyInfoList[j].Name == columnName)
{
xlsEntity = new XlsEntity();
xlsEntity.ColumnName = columnName;
xlsEntity.EntityName = propertyInfoList[j].Name;
xlsEntity.ColumnIndex = i;
xlsHeader.Add(xlsEntity);
break;
}
}
}
#endregion #region 根据对应的实体名列名的对应绑定就行值的绑定 for (int row = rowStart + 1; row <= rowEnd; row++)
{
T result = new T();
foreach (PropertyInfo p in propertyInfoList)
{
var xlsRow = xlsHeader.FirstOrDefault(e => e.EntityName == p.Name);
if (xlsRow == null || xlsRow?.ColumnIndex == 0) continue; ExcelRange cell = worksheet.Cells[row, xlsRow.ColumnIndex];
if (cell.Value == null) continue; try
{
if (xlsRow.ConvertFunc != null)
{
object entityValue = xlsRow.ConvertFunc(cell.Value.ToString());
p.SetValue(result, entityValue);
}
else
{
cellBindValue(result, p, cell);
}
}
catch (Exception ex)
{
if (result.ErrColumn == null) result.ErrColumn = new List<string>();
if (result.ErrMessage == null) result.ErrMessage = new List<string>();
if (result.ErrValue == null) result.ErrValue = new List<string>();
result.ErrColumn.Add(p.Name);
result.ErrMessage.Add(ex.Message);
result.ErrValue.Add(cell.Value.ToString());
result.IsErr = true;
}
}
resultList.Add(result);
}
#endregion
}
return resultList;
} private static void cellBindValue(T result, PropertyInfo p, ExcelRange cell)
{
switch (p.PropertyType.Name.ToLower())
{
case "string":
p.SetValue(result, cell.GetValue<String>());
break;
case "int16":
p.SetValue(result, cell.GetValue<Int16>());
break;
case "int32":
p.SetValue(result, cell.GetValue<Int32>());
break;
case "int64":
p.SetValue(result, cell.GetValue<Int64>());
break;
case "decimal":
p.SetValue(result, cell.GetValue<Decimal>());
break;
case "double":
p.SetValue(result, cell.GetValue<Double>());
break;
case "datetime":
p.SetValue(result, cell.GetValue<DateTime>());
break;
case "boolean":
p.SetValue(result, cell.GetValue<Boolean>());
break;
case "byte":
p.SetValue(result, cell.GetValue<Byte>());
break;
case "char":
p.SetValue(result, cell.GetValue<Char>());
break;
case "single":
p.SetValue(result, cell.GetValue<Single>());
break;
default:
p.SetValue(result, cell?.Value?.ToString());
break;
}
} private static string GetPropertyName(Expression<Func<T, object>> expression)
{
Expression expressionToCheck = expression;
bool done = false;
while (!done)
{
switch (expressionToCheck.NodeType)
{
case ExpressionType.Convert:
expressionToCheck = ((UnaryExpression)expressionToCheck).Operand;
break;
case ExpressionType.Lambda:
expressionToCheck = ((LambdaExpression)expressionToCheck).Body;
break;
case ExpressionType.MemberAccess:
var memberExpression = ((MemberExpression)expressionToCheck);
string propertyName = memberExpression.Member.Name;
return propertyName;
default:
done = true;
break;
}
}
return "";
} } public class XlsEntity
{
/// <summary>
/// 实体名称
/// </summary>
public string EntityName { get; set; } /// <summary>
/// 列名称
/// </summary>
public string ColumnName { get; set; } /// <summary>
/// 列下标
/// </summary>
public int ColumnIndex { get; set; } /// <summary>
/// 转换方法
/// </summary>
public Func<string, object> ConvertFunc { get; set; }
} public class XlsRow
{
/// <summary>
/// 错误信息
/// </summary>
public List<string> ErrMessage { get; set; } /// <summary>
/// 错误列名
/// </summary>
public List<string> ErrColumn { get; set; } /// <summary>
/// 错误内容
/// </summary>
public List<string> ErrValue { get; set; } /// <summary>
/// 是否转换出错(false:未出错,true:出错)
/// </summary>
public bool IsErr { get; set; }
}

使用

  

public async Task<byte[]> ExportExcel(Params param)

        {

            List<Entity> list = await GetDataSource(param).ToListAsync();

            //导出表头和字段集合

            ExportColumnCollective ecc = new ExportColumnCollective();

            //导出字段集合

            ecc.ExportColumnList = new List<ExportColumn>

            {

                new ExportColumn{ Field = "UserId" },

                new ExportColumn{ Field = "UserName" },

            };

            //导出表头集合

            ecc.HeaderExportColumnList = new List<List<ExportColumn>>

            {

                new List<ExportColumn>

                {

                    new ExportColumn{ Title = "用户编号" },

                    new ExportColumn{ Title = "姓名" }

                }

            };

            byte[] result = Export2Excel.Export<BillEntity>(list, ecc, "用户", false);

            return result;

        }
public async Task<FileResult> ExportExcel([FromQuery] BillParams pairs)
{
byte[] result = await _billService.ExportExcel(pairs);
return File(result, "application/vnd.ms-excel", $"{DateTime.Now.ToString("yyMMddHHmmssfff")}.xlsx");
}

导出数据EPPlus的更多相关文章

  1. 1.ASP.NET MVC使用EPPlus,导出数据到Excel中

    好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件. 源代码下载:https://github.com/caofangshe ...

  2. CRL快速开发框架系列教程九(导入/导出数据)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  3. Vertica 导出数据测试用例

    需求:构建简单的测试用例,完成演示Vertica导出数据的功能. 测试用例:导出test业务用户t_jingyu表中的数据. 一.初始化测试环境 二.导出数据 2.1 vsql命令说明帮助 2.2 导 ...

  4. 导出数据到Excel --使用ExcelReport有感

    先看图,这是几个月前用NPOI写的导出数据到Excel,用了上百行代码,而且难控制,导出来也比较难看 excel打开的效果 下面是我用ExcelReport类库导出到Excel的操作 1.首先引用Ex ...

  5. MySQL 导出数据

    MySQL中你可以使用SELECT...INTO OUTFILE语句来简单的导出数据到文本文件上. 使用 SELECT ... INTO OUTFILE 语句导出数据 以下实例中我们将数据表 cnbl ...

  6. 使用Open xml 操作Excel系列之二--从data table导出数据到Excel

    由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...

  7. Dynamics CRM导出数据到Excel

    原创地址:http://www.cnblogs.com/jfzhu/p/4276212.html 转载请注明出处 Pivot Table是微软BI的一个重要工具,所以这里讲一下Dynamics CRM ...

  8. java 导出数据为word文档(保持模板格式)

    导出数据到具体的word文档里面,word有一定的格式,需要保持不变 这里使用freemarker来实现: ①:设计好word文档格式,需要用数据填充的地方用便于识别的长字符串替换  如  aaaaa ...

  9. PHP导出数据到CSV文件函数 csv_export()

    后台往往需要导出各种数据到 Excel文档中.通常我们是导出 .csv文件格式,PHP导出函数参考代码如下: /** * 导出数据到CSV文件 * * @param array $data 二维数组( ...

  10. oracle导入导出数据

    导入数据,cmd   imp 导出数据,cmd   exp

随机推荐

  1. C#生成Guid的几种方式-迷恋自留地

    var uuid = Guid.NewGuid().ToString(); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12 var uuidN = Guid.NewGu ...

  2. 【Amadeus原创】docker中修改wordpress上传文件大小

    1,进入docker 2,cp php.ini 3,   cd到目录 [root@3 ~]# docker exec -it wordpress /bin/bash root@1d8a4fbdaa6b ...

  3. 使用 .NET Core 实现一个自定义日志记录器

    目录 引言 1. 抽象包 1.1 定义日志记录接口 1.2 定义日志记录抽象类 1.3 表结构迁移 2. EntityFramework Core 的实现 2.1 数据库上下文 2.2 实现日志写入 ...

  4. CompilerGenerated与GeneratedCode区别

    前言 最近在捣鼓代码生成器,基于 Roslyn,我们可以让生成器项目生成我们的目标 C# 代码,这个也是MVVM Toolkit的实现方式,在查看生成代码的过程中,我们经常会遇到一些特殊的特性,如 G ...

  5. Tesseract开源的OCR工具及python pytesseract安装使用

    一 .介绍 Tesseract是一款由Google赞助的开源OCR. pytesseract是python包装器,它为可执行文件提供了pythonic API. Tesseract 已经有 30 年历 ...

  6. Qt数据库应用22-文件编码格式识别

    一.前言 在做数据导入导出的过程中,如果应用场景多了,相信各位都会遇到一个问题就是文件编码的问题,有些文件是ANSI编码,有些是utf8编码,有些又是utf8带bom编码,不同的文件编码如果都用同一种 ...

  7. 即时通讯技术文集(第19期):IM架构设计基础知识合集 [共13篇]

    为了更好地分类阅读 52im.net 总计1000多篇精编文章,我将在每周三推送新的一期技术文集,本次是第19 期. [-1-] 微信后台基于时间序的新一代海量数据存储架构的设计实践 [链接] htt ...

  8. 【译】在分析器中使用 Meter Histogram(直方图)解锁见解

    您是否正在与应用程序中的性能瓶颈作斗争?不要再观望了!Visual Studio 2022 在其性能分析套件中引入了 Meter Histogram(直方图)功能,为您提供了前所未有的分析和可视化直方 ...

  9. Diary -「PKUSC 2022」浅谈一类 emo 文学在 OI 游记中的运用

      我突然发现这是我第一次完成这样一篇游记--   一篇记录了绝对意义上"爆炸"的游记.   SC 的前几天,我被一些奇怪的理由说服停课.省选已经过去了吧,机房里除了我全是省队.不 ...

  10. JAVA8 函数式编程(1)- Lambda表达式

    1 简介 简洁的代码就能处理大型数据集合,让复杂的集合处理算法高效的运行在多核CPU上. 面向对象编程是对数据进行抽象,而函数式编程是对行为进行抽象,能编写出更易读的代码--这种代码更多地表达了业务逻 ...