Excel file from Controller

Very easy way to create Excel quickly....

public void ExcelResults(int id)
{
         Business.Agreement_Provider agr = new Business.Agreement_Provider();
         List<MyModel> model = new List<MyModel>();
         var agreements = agr.getExpiringAgreements(id);
         model = agreements.ToList();
         model.OrderBy(p => p.My_Number);

         Export export = new Export();
         export.ToExcel(Response, model);
       
}

Two methods  - Call the first one from the page and then it uses the public
Export class to return a file. The nice thing about the Export class is that we are passing our model in as an object   - this allows us to reuse this same class for any model.

public class Export
        {
            public void ToExcel(HttpResponseBase Response, object myList)
            {
                var grid = new System.Web.UI.WebControls.GridView();
                var thisDate = DateTime.Now.ToShortDateString().Replace("/","_");
                grid.CssClass = "table table-bordered table-striped table-condensed";
                grid.DataSource = myList;
                grid.DataBind();
                Response.ClearContent();
                Response.AddHeader("content-disposition",
                  "attachment; filename=MyFileName_" + thisDate + ".xls");
                Response.ContentType = "application/excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
             
                grid.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
            }
        }

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax