Export excel data from web user control's gridview in C# and ASP.net

Rajnilari2015
Posted by Rajnilari2015 under ASP.NET category on | Points: 40 | Views : 3044
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#EFF3FB" />

<EditRowStyle BackColor="#2461BF" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>



</div>

<br />

<asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click"

Text="Export To Excel" />


and in code behind:-

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

GridView1.DataSource = BindData();

GridView1.DataBind();

}

}



private string ConnectionString

{

get { return @"<SQL Data Source>"; }

}



private DataSet BindData()

{

// make the query

string query = "SELECT * FROM tblTest";

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "TestTable");

return ds;

}





protected void Button1_Click(object sender, EventArgs e)

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

Response.Charset = "";

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =

new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)

{

// Confirms that an HtmlForm control is rendered for the

//specified ASP.NET server control at run time.

}

Comments or Responses

Login to post response