using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
namespace Admin.NET.Core.Helper.ExcelHelper
{
///
/// 导出EXCEL抽象类
///
///
public abstract class ExcelBaseResult: ActionResult
{
#region 属性
///
/// 数据实体
///
public IList Entity { get; set; }
///
/// 下载文件名称(不包含扩展名)
///
public string FileName { get; set; }
///
/// 是否显示标题
///
public bool ShowTitle { get; set; }
///
/// 标题
///
public string Title { get; set; }
///
/// ContentType
///
public string ContentType { get; set; }
///
/// 扩展名
///
public string ExtName { get; set; }
///
/// 获取下载文件全名
///
public string FullName { get { return FileName + ExtName; } }
#endregion
#region 构造函数
public ExcelBaseResult(IList entity, string fileName, bool showTitle, string title)
{
this.Entity = entity;
this.FileName = fileName;
this.ShowTitle = showTitle;
this.Title = title;
}
#endregion
#region 抽象方法
public abstract MemoryStream GetExcelStream();
#endregion
#region 重写ExecuteResult
public override void ExecuteResult(ActionContext context)
{
using (MemoryStream ms = GetExcelStream())
{
context.HttpContext.Response.Headers.Add("Content-Length", ms.Length.ToString());
context.HttpContext.Response.ContentType = ContentType;
context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" +FullName);
ms.Seek(0, SeekOrigin.Begin);
Stream output = context.HttpContext.Response.Body;
byte[] bytes = new byte[1024 * 10];
int readSize = 0;
while ((readSize = ms.Read(bytes, 0, bytes.Length)) > 0)
{
output.WriteAsync(bytes, 0, readSize);
output.FlushAsync();
}
}
}
#endregion
}
}