Wednesday 19 November 2014

Export Functionality in MVC


Exporting a data or report to Excel/PDF is one of the most common functionality required in enterprise application in ASP.NET MVC. This blog includes the code for export functionality.

By calling ExportToExcel ActionResult method, PDF or Excel will be generated with given datasource.

Controller - Home


public ActionResult Index()
{
            return View();
}
public ActionResult ExportToExcel()
{
            List<myList> oReportList = new getList()

            System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();
            gv.DataSource = oReportList;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
          
            Response.AddHeader("content-disposition", "attachment; filename=AttendanceReport.xls");
            Response.ContentType = "application/ms-excel";

            //For PDF
            //Response.AddHeader("content-disposition","attachment;filename=AttendanceReport.pdf");
            //Response.ContentType = "application/pdf";

            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return Json("Success");
 }


Our view will be look like below. Here is shown a code how ExportToExcel button can call from any page.

View : Index

  @using (Html.BeginForm("ExportToExcel", "Home", FormMethod.Post, new { id = "iReportForm" }))
   {
     <button id="iExport" value="ExportToExcel" class="btn green" type="submit">Export To Excel</button>
   }


No comments:

Post a Comment