public class ExcelResult<t> : ActionResult { public string FileName { get; set; } public List<t> Model { get; set; } public override void ExecuteResult(ControllerContext context) { if (Model == null) throw new InvalidOperationException("Model not provided"); if (string.IsNullOrEmpty(FileName)) throw new InvalidOperationException("File name not provided"); HttpResponseBase response = context.HttpContext.Response; response.Buffer = true; response.Clear(); XmlSerializer serializer = new XmlSerializer(Model.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, Model); stream.Seek(0, SeekOrigin.Begin); XDocument doc = Xdocument.Load(stream); response.AddHeader("content-disposition", "attachment; filename=" + FileName); response.ContentType = "application/vnd.ms-excel"; doc.WriteTo(new XmlTextWriter(response.Output)); } } }
MVC Export Entity To Excel
Page 1 of 11 Replies - 23767 Views - Last Post: 09 March 2012 - 11:46 PM
#1
MVC Export Entity To Excel
Posted 09 March 2012 - 11:46 PM
Description: add an ExcelResult to your controller, call the action using an Html.ActionLink or some other meansExport a List of Entity Objects to excel. Makes use of the fact that excel can parse xml data to build tables
Replies To: MVC Export Entity To Excel
#2
Re: MVC Export Entity To Excel
Posted 09 March 2012 - 11:46 PM
Description: add an ExcelResult to your controller, call the action using an Html.ActionLink or some other meansExport a List of Entity Objects to excel. Makes use of the fact that excel can parse xml data to build tables
public class ExcelResult<T> : ActionResult { public string FileName { get; set; } public List<T> Model { get; set; } public override void ExecuteResult(ControllerContext context) { if (Model == null) throw new InvalidOperationException("Model not provided"); if (string.IsNullOrEmpty(FileName)) throw new InvalidOperationException("File name not provided"); HttpResponseBase response = context.HttpContext.Response; response.Buffer = true; response.Clear(); XmlSerializer serializer = new XmlSerializer(Model.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, Model); stream.Seek(0, SeekOrigin.Begin); XDocument doc = Xdocument.Load(stream); response.AddHeader("content-disposition", "attachment; filename=" + FileName); response.ContentType = "application/vnd.ms-excel"; doc.WriteTo(new XmlTextWriter(response.Output)); } } }
Page 1 of 1