In this article we will discuss how to export gridview data to excel sheet in asp.net. Also you can check Advantages of WCF in Asp.Net.
Below is the full code:
Below is the full code:
protected void
btnExport_Click(object sender, EventArgs e)
{
DataSet
ds = new DataSet();
ds = GetDataForGridView();
string
attachment = attachment = "attachment;
filename=MyExcelSheetName_" + DateTime.Now.ToString()
+ ".xls";
if
(ds.Tables.Count > 0)
{
DataTable
dt = ds.Tables[0];
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string
tab = "";
//This
will give you the number of columns present in gridview
for
(int coulumns = 0; coulumns <
GridView1.Columns.Count; coulumns++)
{
Response.Write(tab +
GridView1.Columns[coulumns].HeaderText);
tab = "\t";
}
Response.Write("\n");
//Here we
will visit each row of datatable and bind the corresponding column data.
foreach
(DataRow dr in
dt.Rows)
{
tab = "";
Response.Write(tab + dr["ColumnName1"].ToString());
tab = "\t";
Response.Write(tab + dr["ColumnName2"].ToString());
tab = "\t";
Response.Write(tab + dr["ColumnName3"].ToString());
tab = "\t";
Response.Write("\n");
}
Response.End();
}
}