Export the grid data to excel
protected void btnExport_Click(object sender, EventArgs e)
{
ExportGridToExcel();
}
private void ExportGridToExcel()
{
try
{
con.Open();
SqlCommand com; SqlDataAdapter ad;
com = new SqlCommand("select fname as FirstName,email as EmailId,contact as ContactNo,nopax as NoPax,hotelcate as HotelCategory,country as Country,convert(varchar,traveldate,103) as TravelDate,custdetail as CustomizeDetails,status as Status,enqdate as EnquiryDate from customize", con);
ad = new SqlDataAdapter();
ad.SelectCommand = com;
DataTable dt = new DataTable();
ad.Fill(dt);
GridView gd = new GridView();
gd.DataSource = dt;
gd.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Branch.xls");
Response.ContentType = "application/ms-excel";
string k = GetGridViewHtml(gd);
Response.Write(k);
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
public string GetGridViewHtml(Control c)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
c.RenderControl(hw);
return sw.ToString();
}