Step 1 : - Write the Following Code to your Default.aspx.cs file.
protected void Page_Load(object sender, EventArgs e)
{
ExportToXLS();
}
private void ExportToXLS()
{
StringWriter sw
= new StringWriter();
HtmlTextWriter htw
= new HtmlTextWriter(sw);
GridView1.Visible = true;
GridView1.AllowPaging = false;
GridView1.DataSource = GetData();
GridView1.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;
filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
//Formating
the excel to add header above with following details
htw.WriteLine("<center><b><u><font
size='4'></br></br>ABC Co. Ltd. </font> </u>
</b></center></br>");
htw.WriteLine("<center><b><u><font
size='3'>Report Name </font> </u>
</b></center></br>");
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public DataTable GetData()
{
DataTable dtTable
= new DataTable();
SqlConnection con
= new SqlConnection(@"Data
Source=Your Server IP;Initial Catalog=Your Database Name;User Id=Your Database
User ID;Password=Your Database Password");
SqlCommand com
= new SqlCommand();
com.CommandText = "select * from Test";
com.CommandType = CommandType.Text;
com.Connection = con;
con.Open();
SqlDataAdapter adpt
= new SqlDataAdapter(com);
adpt.Fill(dtTable);
con.Close();
return dtTable;
}
Note : - USE THIS METHOD IN CODE
BEHIND WHEN YOU ARE USING ContentPlaceHolder
public override void VerifyRenderingInServerForm(Control control)
{
}
No comments:
Post a Comment