Hi,
If your filling your grid view by fetching data from database then following will be useful to you...
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
string strconstring = ConfigurationManager.AppSettings["con"]; //database connection string from web.config file
SqlConnection cn = new SqlConnection(strconstring); // connection to DB
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
string strSQL = "";
cn.Open();
strSQL = "select * from table1 "; //your select query which display data in gridview
<pre lang="text">
}
da.SelectCommand = new SqlCommand(strSQL, cn);
da.Fill(dt);
//DataTable dt = new DataTable();
//dt = (DataTable)Session["MonthlyCostingData"];
Response.Clear();
string attachment = "attachment; filename=AfterSalesPerformance_" + DateTime.Now.Date.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
//dr[i].Style.Add("background-color", "#FFFFC0");
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
#endregion
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}