我创建了一个文件,该文件将来自gridview的所有详细信息存储到CSV文件中。
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");
}
上面的代码只是将文件保存到计算机中。
我需要一些代码才能直接下载数据集
答案 0 :(得分:1)
您可以在onclick_btnExportToExcel事件的代码末尾添加以下代码。另外,请删除显示消息的行,因为浏览器将处理向用户显示相关下载消息的情况。
//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();