Monday, 3 September 2012

Export Datatable to Excel using C#


  protected void Button1_ServerClick(object sender, EventArgs e)
    {
        DataTable dtnew = null;
        try
        {
            string filename = "Detail.csv";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dtnew = YourDataTable; 
            dgGrid.DataSource = dtnew;
            dgGrid.DataBind();
            dgGrid.RenderControl(hw);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
        catch (OutOfMemoryException oex)
        {
            lblError.Text = "Sorry!Data is too large to export";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

 

No comments:

Post a Comment