In Default.aspx
<asp:gridview id="gv" runat="server" >
</asp:gridview>
<asp:button id="btnsend" runat="server" text="Export to Excel" onclick="btnsend_Click" />
In Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack != true)
{
BindGrid();
}
}
private void BindGrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=aa; User Id=aa; Password=aa; Initial Catalog=aa; Integrated Security=xxxx";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from student_info";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
gv.DataSource = dt;
gv.DataBind();
}
protected void btnsend_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=abc.doc");
Response.ContentType = "application/vnd.ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
BindGrid();
gv.RenderControl(hw);
Response.Output.Write(sw.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. */
}