Search code examples
c#asp.net-mvcasp.net-mvc-4export-to-excel

Export to Excel not working in ASP.NET MVC 4


I have a code that will generate an excel report.i am using ASP.NET MVC 4. I googled and found the same code everywhere still my code is not working why. My code in controller is as:

public ActionResult ExportData()
{
     string[] abc = { "AAA", "BBB", "CCC" };
     GridView gv = new GridView();
     gv.DataSource = abc;
     gv.DataBind();
     Response.ClearContent();
     Response.Buffer = true;
     Response.AddHeader("content-disposition", "attachment; filename=Marklist.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 RedirectToAction("_EligibilityCriteria");  
} 

Just to test the export functionality I used an array abc this code is working in .net application but not in ASP.NET MVC 4 application. I have debugged the code but not found a problem or error in code.

What am I doing wrong here?


Solution

  • Finally found a way to export to excel.

     public void ExportIniEmployeeToExcel(EligibilityCriteriaModel AllIniEmp)
        {
            List<AllIniEmployees> emp = new List<AllIniEmployees>();            
            AllIniEmp.allSuccessEmployeeList.ForEach(x =>
                {
                    AllIniEmployees allEmp = new AllIniEmployees();
                    allEmp.EmployeeCode = x.EmployeeCode;
                    allEmp.EmployeeName = x.EmployeeName;
                    allEmp.Designation = x.Designation;
                    allEmp.DeliveryTeam = x.DeliveryTeam;
                    allEmp.ConfirmationDate = x.ConfirmationDate;
                    emp.Add(allEmp);
                });
            GridView gv = new GridView();
            gv.DataSource = emp;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=InitiatedEmployees.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();
        }
    

    here i used parent class as a parameter and used linq.now its working perfectly fine. thank you all.