Tuesday, July 3, 2012

Export component art grid to excel

Following code can be used to export component art grid or asp.net grid to excel

 protected void Page_Load(object sender, EventArgs e)
        {
 ExportToExcel(DataTable, Response, "Excel Sheet-" + DateTime.Today.ToString("MM-dd-yyyy"));
 }

 public void ExportToExcel(DataTable dataTable, HttpResponse Response, string FileName)
        {
            Response.Clear();
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xlsx");
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            GridView gv = new GridView();
            gv.DataSource = dataTable;
            gv.DataBind();
            gv.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
        }

No comments:

Post a Comment