CoreSpider - Export to Excel in ASP.NET MVC
[HttpPost] | |
public ActionResult Export() | |
{ | |
// Step 1 - get the data from database | |
var data = GetCustomer(); | |
// instantiate the GridView control from System.Web.UI.WebControls namespace | |
// set the data source | |
GridView gridview = new GridView(); | |
gridview.DataSource = data; | |
gridview.DataBind(); | |
// Clear all the content from the current response | |
Response.ClearContent(); | |
Response.Buffer = true; | |
// set the header | |
Response.AddHeader("content-disposition", "attachment;filename = data.xls"); | |
Response.ContentType = "application/ms-excel"; | |
Response.Charset = ""; | |
// create HtmlTextWriter object with StringWriter | |
using (StringWriter sw = new StringWriter()) | |
{ | |
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) | |
{ | |
// render the GridView to the HtmlTextWriter | |
gridview.RenderControl(htw); | |
// Output the GridView content saved into StringWriter | |
Response.Output.Write(sw.ToString()); | |
Response.Flush(); | |
Response.End(); | |
} | |
return View(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment