如何通过单击按钮(asp.net)下载文件?

Siddhant Shah

我创建了一个文件,该文件将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");
}

上面的代码只是将文件保存到计算机中。

我需要一些代码来直接下载数据集

苏尼尔

您可以在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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章