In a scenario comes on asp.net MVC application comes where user need to export in excel , csv, xml file by asp.net MVC application as tabular data.
Image may be NSFW.
Clik here to view.
So on export button form will be submitted and execute controller’s POST Method.
So in POST method load all data and export in excel with below code, Also if any filter applied then that filter parameter need pass as parameter in post method and execute data based on that filter to before export in excel.
public ActionResult ExportData() { var employeeDetail = from e in DB.employees.AsEnumerable() select new { e.firstname, e.lastname, e.emailid, e.addresss }; System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView(); gridvw.DataSource = employeeDetail.ToList().Take(7); //bind the datatable to the gridview gridvw.DataBind(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment;filename=employeeDetail.xls"); Response.ContentType = "application/excel"; StringWriter swr = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(swr); gridvw.RenderControl(tw); Response.Write(swr.ToString()); Response.End(); return View("About", employeeDetail); }
Please post a comment if you have any more questions.
Thanks,
Amit Patel
“Enjoy Programming”
Image may be NSFW.
Clik here to view.

Clik here to view.
