Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to export GridView to Excel in .Net

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 177
    Comment on it

    Hello all,

    In asp.net we show our database records in tabular format using GridView control and to export that GridView Data to excel, we can use following code packet.

    protected void gridViewExportToExcel()
        {
            if (GridView.Rows.Count > 0)
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=ExporttoExcel.xls");
                Response.Charset = string.Empty;
                Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
                Response.ContentType = "application/ms-excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                Table table = new Table();
                table.GridLines = GridView.GridLines;
                table.Rows.Add(GridView.HeaderRow);
                for (int i = 0; i < GridView.Rows.Count; i++)
                {
                    GridViewRow row = GridView.Rows[i];
                    //Apply text style to each Row
                    row.Attributes.Add("class", "textmode");
                    table.Rows.Add(row);
                }
                table.RenderControl(hw);
                string style = @"";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
            else
            {
                string script = "<script language="javascript"> alert('No data to export');";
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "Alert Message", script, false);
            }
        }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: