asp.net中导出Excel通用型

前端请求:

<a class="btn btn-default ml-50" href="javascript:Out_Excel();">导出Excel</a>  

function Out_Excel() {
var bdate = $("#tisStartTime").val();
var edate = $("#titsEndTime").val();
var useridx = $("#useridx").val();
window.location.href = "/ActivityManagement/ExportExcel?bdate=" + bdate + "&edate=" + edate + "&useridx=" + useridx;
}

 

后台处理请求:

int pagesize = int.MaxValue;
if (bdate == null || edate == null)
{
bdate = DateTime.Today.AddDays(-30);
edate = DateTime.Today.AddDays(1);
}

//这里的useridx  page pagesize bdate edate 导出时的条件
List<CashDetailsList> stuList = server.CashDetailsList(useridx, page, pagesize, bdate, edate);
stuList.Export("星探提现明细");

///Export这里是导出操作封装的通用类,在做所有导出只要传一个参数就是导出文件的名称就行

 

下面就是通用型导出的核心

  首先将List<CashDetailsList>添加一个扩展类型 ,目的是要得到一个stuList.Export(“”“”)

public static void Export<T>(this IEnumerable<T> list, string fileName) where T : new()
{
ExcelHelper<T>.Export(list, fileName);
}

 

然后再封装一个类,这里存放导出的操作

using MaoLiao.Infrastructure.Attributes;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MaoLiao.Common
{
// Excel相关操作
// 依赖项: NPOI(2.3.0) Nuget 添加命令:Install-Package NPOI -Version 2.3.0
// NPOI(2.3.0)依赖项 SharpZipLib (>= 0.86.0)

 

//注意这里的静态类,再调用时需要传一个对象,如果是静态变量,会只执行一次

///这步操作目的是,遍历出实体类中的属性和名字,实体类的写法例如:

[Export("编号")]
public int rowid { get; set; }
public int count { get; set; }
[Export("用户IDX")]
public long useridx { get; set; }
[Export("用户名")]
public string myName { get; set; }
[Export("支付宝账户")]

 

public class ExcelHelper<T> where T : new()
{
private static List<ColumnInfo> _columns;  ///将得到的实体类属性和名称存入泛型集合中
static ExcelHelper()
{
_columns = new List<ColumnInfo>();
foreach (var pro in typeof(T).GetProperties())
{
ExportAttribute attribute = (ExportAttribute)pro.GetCustomAttribute(typeof(ExportAttribute)); ///得到实体中的属性
if (attribute != null)
{
_columns.Add(new ColumnInfo() { name = attribute.columnName, property = pro }); ////得到实体中的名称
}
}
}

//////////////////////////////////////////////////////////////////

 

 

////这一步是设置导出的一些属性,字符节,导出文件名称

public static void Export(IEnumerable<T> list, string fileName)
{
HttpContext curContext = HttpContext.Current;
if (curContext != null)
{
if (!fileName.EndsWith(".xls") && !fileName.EndsWith(".xlsx"))
{
fileName += ".xls";
}
using (MemoryStream stream = IEnumerableToStream(list))
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "UTF-8";
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
curContext.Response.BinaryWrite(stream.ToArray());
curContext.Response.End();
}
}
}

 

 

 

/////////遍历泛型集合得到行和列

private static MemoryStream IEnumerableToStream(IEnumerable<T> list)
{
HSSFWorkbook book = new HSSFWorkbook();
ISheet sheet1 = book.CreateSheet("Sheet1");

//列
IRow titles = sheet1.CreateRow(0);
int col = 0;
foreach (var c in _columns)
{
titles.CreateCell(col++).SetCellValue(c.name);
}

//行
int row = 1;
foreach (var entity in list)
{
col = 0;
IRow _row = sheet1.CreateRow(row++);
foreach (var c in _columns)
{
object value = c.property.GetValue(entity);
string cellValue = value == null ? string.Empty : value.ToString();
_row.CreateCell(col++).SetCellValue(cellValue);
}
}
using (MemoryStream stream = new MemoryStream())
{
book.Write(stream);
return stream;
}
}
}

public class ColumnInfo
{
public string name { get; set; } //得到属性名称
public PropertyInfo property { get; set; } //得到属性
}

}

 

 

////以上就是本人将导出Excel,封装成通用型的一些见解,才疏学浅,还望指教。

 

 

  

 

posted @ 2018-07-12 10:09  ITMrRight  阅读(143)  评论(0编辑  收藏  举报