不多BB 直接上完整代码。
//该特性表示此属性可导出到Excel:
[AttributeUsage(AttributeTargets.Property)]
public class ExportAttribute : Attribute
{
/// <summary>
/// 导出展示的列名
/// </summary>
/// <param name="columnName"></param>
public ExportAttribute(string columnName)
{
this.columnName = columnName;
}
/// <summary>
/// 导出展示的列名
/// </summary>
public string columnName { get; set; }
}
model类:
export定义导出的字段
public class VideoTalkOrderLog
{
public long id { get; set; }
[Export("IDX")]
public long useridx { get; set; }
[Export("姓名")]
public string myName { get; set; }
[Export("主播类型")]
public int anchorType { get; set; }
[Export("家族ID")]
public long roomid { get; set; }
[Export("家族昵称")]
public string familyName { get; set; }
[Export("通话次数")]
public long callcount { get; set; }
//用户总拨打次数
[Export("总拨打次数")]
public long allcount { get; set; }
[Export("通话率")]
public string percentages { get; set; }
[Export("通话时长(分)")]
public long alltime { get; set; }
[Export("好评数")]
public long like { get; set; }
[Export("差评数")]
public long dislike { get; set; }
[Export("累计获得猫粮")]
public long sumCoin { get; set; }
[Export("在线时长(分)")]
public long validtime { get; set; }
[Export("打赏")]
}
控制器中得到要导出的数据后直接执行封装好的泛型扩展方法,传入要导出表格的名字:
//主播通话统计---导出excel主播通话统计列表
public void ExportExcel(DateTime? bdate, DateTime? edate, string myName = "", long? useridx = 0, int page = 1, int anchorType = -1)
{
int pageSize = int.MaxValue;
if (bdate == null || edate == null)
{
bdate = DateTime.Today.AddDays(-7);
edate = DateTime.Today.AddDays(1);
}
List<VideoTalkOrderLog> stuList = service.AnchorCallCount(bdate, edate, myName, useridx, page, pageSize, anchorType);
stuList.Export("通话统计");
}
泛型的扩展方法:
public static class EnumerableExtensions
{
public static void Export<T>(this IEnumerable<T> list, string fileName) where T : new()
{
ExcelHelper<T>.Export(list, fileName);
}
}
扩展方法跳转到封装好的excel类
namespace MaoLiao.Common
{
// Excel相关操作
// 依赖项: NPOI(2.3.0) Nuget 添加命令:Install-Package NPOI -Version 2.3.0
// NPOI(2.3.0)依赖项 SharpZipLib (>= 0.86.0)
public class ExcelHelper<T> where T : new()
{
//泛型中的静态变量
private static List<ColumnInfo> _columns;
static ExcelHelper()
{
_columns = new List<ColumnInfo>();
//利用反射获取到T中公共属性
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; }
}
}