前言

  导出数据在管理系统中经常要用到,目前的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. xlsx.js 表格的导出与导入

    1.xlsx简介 通俗的说,xlsx这个插件可以把html中的table元素或者json数据转换成表格后进行导出 <script src="https://cdn.bootcdn.ne ...

  2. 使用 MOLECULE 迅速包装百度 UEditor

    UEditor: UEditor - 首页http://ueditor.baidu.com/website/ 我们在对话框上放了几个 UEditor,发现第一次弹出对话框时UEditor还没有初始化 ...

  3. Ubuntu终端输入异常、无法退格(删除文本)、使用方向键命令

    1 起因 为了学习嵌入式开发安装去安装的ncurses库,使用命令:sudo apt-get install libncurses5-dev导致系统自带的ncurses-base被自动删除. 2 出现 ...

  4. Unity 3D更换默认脚本编辑器VisualStudio

    由于VisualStudio 30天试用到期了,所有不能编辑Unity 3D脚本.需要更换成Notepad++ 打开Unity 3D顶部菜单 点击编辑(Editor)->Preferences- ...

  5. Qt开发经验小技巧276-280

    对MDI窗体区域设置背景颜色透明,会发现 QMdiArea{background:transparent;} 无效,哪怕是指定颜色 QMdiArea{background:#ff0000;} 或者 Q ...

  6. vue引入element-ui插件 “export ‘default‘ (imported as ‘Vue‘) was not found in ‘vue‘

    注意:出现该问题的原因主要是使用的Vue版本与Element-UI的版本不匹配. Vue.Vue-cli与Element-UI之间版本的正确的匹配关系是: Vue库版本 Vue-cli库版本 Elem ...

  7. IntelliJ IDEA打开Spring Booot项目并使用Maven导入依赖包时提示错误:Cannot resolve com.gexin.platform:gexin-rp-sdk-http:4.1.0.5

    构建项目时报错:  Cannot resolve com.gexin.platform:gexin-rp-sdk-http:4.1.1.4 gexin-rp-sdk-http:jar:4.1.1.4总 ...

  8. IDEA中基于SSM框架进行web开发部署项目到Tomcat时报错:Error:Cannot build artifact '******:war exploded' because it is included into a circular depency的解决办法

    在Idea中使用Maven创建父子工程,第一个Model的那个项目可以很好的运行,在创建一个Model运行时报这个错.原因是tomcat部署了多个Web项目,可能最开始是两个项目的配置文件混用用,最后 ...

  9. 一步一步abp电商模块-1、搭建模块环境

    前言 目前在开发abp电商模块,打算做一步,写一步,算是对自己的记录,主要是参考nopcommoner 并结合abp模块开发 知识都是连贯的,如果你熟悉asp.net core 3.x.abp(非vN ...

  10. c# 远程调用 / Remoting IpcChannel sample

    . 远程调用 1. 创建一个远程的可序列化的类,这个类可以在远程调用中用于传输来去,似乎是个公共的类: using System; using System.Collections.Generic; ...