Monday, 15 September 2014

How to Export Data From GridView to Excel using Asp.net C#

How to Export Data From GridView to Excel using Asp.net C#

Following are the Steps:

1.AddGridview in Default.aspx.and bind it on pageload.

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Untitled Page</title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:GridViewID="gridBind"runat="server"Style="font-size: 14px; padding: 4px;">
<RowStyleBackColor="#FFF7E7"ForeColor="#8C4510"/>
<FooterStyleBackColor="#F7DFB5"ForeColor="#8C4510"/>
<PagerStyleForeColor="#8C4510"HorizontalAlign="Center"/>
<SelectedRowStyleBackColor="#738A9C"Font-Bold="True"ForeColor="White"/>
<HeaderStyleBackColor="#336600"Font-Bold="True"ForeColor="White"/>
</asp:GridView>
<asp:ButtonID="btn_export"runat="server"Text="Export To Excel"OnClick="btn_export_Click"/>
</div>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.IO;
publicpartialclass_Default : System.Web.UI.Page
{
SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["stringConnection"].ToString());

SqlDataAdapter da;

SqlCommand cmd;
protectedvoid Page_Load(object sender, EventArgs e)
    {
        bindData();

    }
protectedvoid bindData()
    {
if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

String qry = "Select name,address,mobile From user_mst";
            cmd = newSqlCommand(qry, con);

DataSet ds = newDataSet();
            da = newSqlDataAdapter(cmd);
            da.Fill(ds);
if (ds != null&& ds.Tables[0].Rows.Count > 0)
            {
                gridBind.DataSource = ds;
                gridBind.DataBind();
            }
else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gridBind.DataSource = ds;
                gridBind.DataBind();
int columncount = gridBind.Rows[0].Cells.Count;
                gridBind.Rows[0].Cells.Clear();
                gridBind.Rows[0].Cells.Add(newTableCell());
                gridBind.Rows[0].Cells[0].ColumnSpan = columncount;
                gridBind.Rows[0].Cells[0].Text = "No Records Found";
            }
            cmd.Dispose();
            con.Close();
            da.Dispose();
    }
publicoverridevoid VerifyRenderingInServerForm(Control control)
    {
    }
protectedvoid btn_export_Click(object sender, EventArgs e)
    {
try
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = newStringWriter())
            {
HtmlTextWriter hw = newHtmlTextWriter(sw);

//To Export all pages
                gridBind.AllowPaging = false;
//  this.BindGrid();

                gridBind.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridBind.HeaderRow.Cells)
                {
                    cell.BackColor = gridBind.HeaderStyle.BackColor;
                }
foreach (GridViewRow row in gridBind.Rows)
                {
                    row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
                    {
if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = gridBind.AlternatingRowStyle.BackColor;
                        }
else
                        {
                            cell.BackColor = gridBind.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                gridBind.RenderControl(hw);

//style to format numbers to string
string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }
catch (Exception)
        {
        }
    }
}


Screen shots:

Download Source Code: Click Here
written by Chandana Das

No comments:

Post a Comment