Coding:
=> Demo.aspx Source code
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="architecture.Demo" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <title></title>
- </head>
-
- <body>
- <form id="form1" runat="server">
- <div> <br /> <br />
- <asp:GridView ID="gvlist" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333">
- <Columns>
- <asp:BoundField DataField="ID" HeaderText="Id" HeaderStyle-Width="200px" />
- <asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="200px" />
- <asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="200px" /> </Columns>
- <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> </asp:GridView> <br />
- <asp:Button ID="btnExport" runat="server" OnClick="Button1_Click" Text="Export To Excel" /> </div> <br /> </br>
- </form>
- </body>
-
- </html>
=>Demo.aspx.cs code behind file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.IO;
- using System.Collections;
- namespace architecture
- {
- public partial class Demo: System.Web.UI.Page
- {
- SqlConnection con;
- DataTable dt;
-
- public static string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- protected void Page_Load(object sender, EventArgs e) {
-
- if (!IsPostBack) {
- ShowData();
- }
- }
-
- protected void ShowData()
- {
- SqlConnection con = new SqlConnection(constr);
- string str = "Select * from TbDemo; select * from TbDemo";
- con.Open();
- SqlCommand cmd = new SqlCommand(str, con);
- DataTable dt = new DataTable();
- SqlDataReader reader = cmd.ExecuteReader();
- dt.Load(reader);
- DataView dv = dt.DefaultView;
- gvlist.DataSource = dv;
- gvlist.DataBind();
- int i = 0;
- con.Close();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AddHeader("content-disposition", "attachment;filename=Users.xls");
- Response.ContentType = "applicatio/excel";
- StringWriter sw = new StringWriter();;
- HtmlTextWriter htm = new HtmlTextWriter(sw);
- gvlist.RenderControl(htm);
- Response.Write(sw.ToString());
- Response.End();
- }
- public override void VerifyRenderingInServerForm(Control control) {}
- }
- }