I have a user control with a Grid. Now I have added an export to excel button on the Same user grid just above the grid to enable user to export the corresponding Grid's data to Excel. I wrote the following function on button click even t in User control.
protected void Home_ExportExcel_Click(object sender, EventArgs args)
{
DataTable resultTbl = new DataTable();
if (this.HomeGridDataSource != null)
resultTbl = this.HomeGridDataSource as DataTable;
Download(resultTbl, this.MasterPage.CurrentLibrary);
}
the Download Function is
private void Download(DataTable tb)
{
string attachment = "attachment; filename=HomeGridData" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in tb.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in tb.Rows)
{
tab = "";
for (i = 0; i < tb.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
Now I get the response for the request as a text format but I need this to be downloaded to the user machine with the Grid data.
I also tried generating .xml file with the Excel styles etc.. but I get the Same result as a text format in response object but I am expecting it to be downloaded.
What am I missing here?