Mvc Excel导出控制器扩展
实现代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Reflection; 7 using System.Text; 8 9 namespace HtmlHelperDemo.Extension 10 { 11 public class ExportExcelResult : ActionResult 12 { 13 private string filename; 14 private IEnumerable<object> source; 15 public ExportExcelResult(IEnumerable<object> source, string filename) 16 { 17 this.source = source; 18 this.filename = filename; 19 } 20 public override void ExecuteResult(ControllerContext context) 21 { 22 if (source != null && source.Any()) 23 { 24 context.RequestContext.HttpContext.Response.AppendHeader("content-disposition", "attachment;filename=" + filename); 25 context.RequestContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("gb2312"); 26 context.RequestContext.HttpContext.Response.ContentType = "application/excel"; 27 object obj = source.FirstOrDefault(); 28 PropertyInfo[] infos = obj.GetType().GetProperties(); 29 foreach (var item in infos) 30 { 31 var cutomeObj = item.GetCustomAttributes(typeof(DescriptionAttribute), false); 32 if (cutomeObj != null && cutomeObj.Any()) 33 { 34 DescriptionAttribute desc = cutomeObj[0] as DescriptionAttribute; 35 context.RequestContext.HttpContext.Response.Write(desc.Descrip); 36 context.RequestContext.HttpContext.Response.Write("\t"); 37 } 38 } 39 context.RequestContext.HttpContext.Response.Write("\n"); 40 foreach (var item in source) 41 { 42 PropertyInfo[] infoarr = item.GetType().GetProperties(); 43 foreach (var info in infoarr) 44 { 45 var val = info.GetValue(item, null); 46 context.RequestContext.HttpContext.Response.Write(val); 47 context.RequestContext.HttpContext.Response.Write("\t"); 48 } 49 context.RequestContext.HttpContext.Response.Write("\n"); 50 } 51 context.RequestContext.HttpContext.Response.End(); 52 } 53 else 54 throw new ArgumentNullException("source can't be null"); 55 } 56 57 } 58 59 60 public class DescriptionAttribute : Attribute 61 { 62 public string Descrip; 63 public DescriptionAttribute(string descrip) 64 { 65 this.Descrip = descrip; 66 } 67 } 68 }
调用代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public ActionResult Index3() 2 { 3 List<Studnet> list = new List<Studnet>(); 4 list.Add(new Studnet() { ID = 1, Name = "aaa" }); 5 list.Add(new Studnet() { ID = 2, Name = "bbb" }); 6 return new ExportExcelResult(list, "aaa.xls"); 7 } 8 public class Studnet 9 { 10 [Description("编号")] 11 public int ID { get; set; } 12 [Description("姓名")] 13 public string Name { get; set; } 14 15 }