Search code examples
asp.net-mvc-4webgrid

How to export MVC webgrid results to pdf and excel directly without using any third party control?(iTEXtSharp i not working)


I have tried itextsharp samples and the serializing to xml . Am using Entity frame work 6.0 and asp.net mvc4


Solution

  • I'm using following for export to excel:

    In your Controller:

    public ActionResult ExportData()
            {
                var datasource = db.Products.ToList(); 
    
                GridView gv = new GridView();
                gv.DataSource = datasource;         
                gv.DataBind();            
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
                Response.ContentType = "application/ms-excel";
                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");
               }
    

    In View:

    @using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
                {           
    
      <button type="Submit">Export to Excel</button>
                }
    
    //OR:
    
    @Html.ActionLink("Export to Excel", "ExportData", "Home")
    

    As to export to PDF, I'd recommend to use Rotativa. Works ok for me.

    EDITED I'm using filters too. You may send it's value from View to controller action and modify datasource. For example:

    public ActionResult ExportData(DateTime fromDate)
                {
                    var datasource = db.Products.Where(g=>g.Date <= fromDate).ToList();