Export data to Excel file with MVC C#

Most of the time  it is required to export data into Excel file in Application. So i have tried many ways but i found very simple code for that.

Sometime we need to hit by ajax call sometimes direct action link. so personally i like direct hit we don't need to redirect anywhere on button click.

i have use this code to export excel file in mvc. let's go through the code.


So on controller level we have to define one method look like-

now you can see here i have defined  void type method not ActionResult.

///controller Action Method
public void ExportExcel()
{
    Export export = new Export();
    export.ExcelExportMethod(Response);
}

Second we have to create class by Export name and under class create one method looks like-

public void ExcelExportMethod(HttpResponseBase Response)
    {
        var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = //need to pass Data in list type;
        grid.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment;            filename=FileName.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }



Third thing we have to put one action button on view page.

 @Html.ActionLink("Export", "ExportExcel","Your Controller Name")


That's it.

Through this code you can Export data in MVC.



Happy codding!

Comments

Popular posts from this blog

Difference between shared, Versioned and Unversioned fileds in sitecore

How to find broken links in Sitecore.

Setup First Sitecore Helix Example From Scratch (Blank solution)