C#_.NetFramework_Web项目_EXCEL数据导出

【推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出

 

项目需引用NPOI的NuGet包:

 

A-2:EXCEL数据导出--Web项目--C#代码导出:

/// 
    /// EXCEL帮助类
    /// 
    /// 泛型类
    /// 泛型类集合
    public class ExcelHelp where T : new() where TCollection : List, new()
    {
        //http请求Request对象
        public static HttpRequest baseRequest = HttpContext.Current.Request;
        //http请求Response对象
        public static HttpResponse baseResponse = HttpContext.Current.Response;/// 
        /// 将数据导出EXCEL
        /// 
        /// 列名+显示名
        /// 数据集(tColl里的类属性名必须和字典中的列名一致)
        public static void ExportExcelData(Dictionary columnNameAndShowNameDic, TCollection tColl)
        {
            WorkBook workbook = WorkBook.CreateNew();
            WorkSheet worksheet = workbook.Sheets["sheet1"];

            List columnNameList = columnNameAndShowNameDic.Keys.ToList();
            List showNameList = columnNameAndShowNameDic.Values.ToList();
            //暂定26行
            string[] zm = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            //设置首列显示
            for (var i = 0; i < columnNameList.Count; i++)
            {
                worksheet.Cells[zm[i] + "1"].Value = showNameList[i];
                //加粗
                worksheet.Cells[zm[i] + "1"].Style.Font.Bold = true;
            }
            for (int i = 0; i < tColl.Count; i++)
            {
                for (int j = 0; j < columnNameList.Count; j++)
                {
                    worksheet.Cells[zm[j] + (i + 2)].Value = getPropertyValue(tColl[i], columnNameList[j]);
                }
            }
            byte[] buffer = workbook.SaveAsBytes();
            baseResponse.Clear();
            baseResponse.Buffer = true;
            baseResponse.ContentEncoding = System.Text.Encoding.UTF8;
            //baseResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            baseResponse.ContentType = "application/vnd.ms-excel";
            //设置导出文件名
            baseResponse.AddHeader("content-disposition", "attachment;  filename=" + "MaintainReport" + ".xlsx");
            baseResponse.AddHeader("Content-Length", buffer.Length.ToString());

            baseResponse.BinaryWrite(buffer);
            baseResponse.Flush();
            baseResponse.End();
        }
        /// 
        /// 获取属性值
        /// 
        /// T对象实例
        /// 属性名
        /// 
        public static string getPropertyValue(T t, string propertyName)
        {
            PropertyInfo info = t.GetType().GetProperty(propertyName);
            //获取属性值转换暂设置如下字段,可根据实际情况添加
            if (info.PropertyType == typeof(DateTime))
            {
                return Convert.ToDateTime(info.GetValue(t)).ToString("yyyy-MM-dd HH:mm");
            }
            return info.GetValue(t).ToString();
        }
    }

你可能感兴趣的:(C#_.NetFramework_Web项目_EXCEL数据导出)