Reputation: 31
I have created a file which stores all the details from the gridview into a CSV file.
protected void onclick_btnExportToExcel(object sender, EventArgs e)
{
var filename = "Error Details"+System.DateTime.Now.ToString("yyyymmddhhmmss")+ ".csv";
StringBuilder sb = new StringBuilder();
var ds1 = DAL_Migration.GetErrorDetails(ViewState["importID"].ToString(), ViewState["filetype"].ToString());
IEnumerable<string> columnNames = ds1.Tables[0].Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in ds1.Tables[0].Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(filename, sb.ToString());
_msgbox.ShowSuccess("File Created");
}
The above code just saves the file into the computer.
I need some code to download the dataset directly
Upvotes: 1
Views: 460
Reputation: 21396
You can add following code at the end of your code in onclick_btnExportToExcel event. Also, remove the line that shows a message since browser will handle showing relevant download message touser.
//get full physical path of file including its name
string fullFileName = Request.PhysicalApplicationPath + fileName;
//read contents of file at above location and modify Response header
//so browser knows response is not html but a csv file content
byte[] Content= File.ReadAllBytes(fullFileName);
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Upvotes: 1