schangxiang@126.com
2025-03-02 7049a601220246aeaae33da5bdb83c167c2dbb45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
 
namespace Admin.NET.Core.Helper.ExcelHelper
{
    /// <summary>
    /// 导出EXCEL抽象类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ExcelBaseResult<T>: ActionResult
    {
        #region 属性
        /// <summary>
        /// 数据实体
        /// </summary>
        public IList<T> Entity { get; set; }
        /// <summary>
        /// 下载文件名称(不包含扩展名)
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// 是否显示标题
        /// </summary>
        public bool ShowTitle { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// ContentType
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// 扩展名
        /// </summary>
        public string ExtName { get; set; }
        /// <summary>
        /// 获取下载文件全名
        /// </summary>
        public string FullName { get { return FileName + ExtName; } }
 
        #endregion
 
        #region 构造函数
        public ExcelBaseResult(IList<T> 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
 
 
    }
}