使用C#和asp.net创建用于保存csv文件的对话框

时间:2017-09-07 11:18:15

标签: c# asp.net csv httpresponse

在我的代码中,我有一个asp转发器,我希望允许用户将数据从此导出到csv文件。导出到csv工作正常但当我希望显示一个对话框供用户选择保存到没有任何反应的位置。我已经经历了几个显然有效的不同解决方案但是当我在我的代码中运行它时没有任何反应,我无法弄清楚为什么。这是我目前的代码:

protected void exportCSV_Click(object sender, EventArgs e)
{
    try
    {
        string FilePath = Server.MapPath("~") + "\\test.csv";
        StringBuilder columnbind = new StringBuilder();
        foreach (Control item in rpt_bookings.Items)
        {
            Literal row1 = (Literal)item.FindControl("ltl_bookingemail");
            Literal row2 = (Literal)item.FindControl("ltl_bookingphone");
            Literal row3 = (Literal)item.FindControl("ltl_bookingcost");
            string fullRow = row1.Text.ToString() + "," + row2.Text.ToString() + "," + row3.Text.ToString();
            columnbind.Append(fullRow);
            columnbind.Append("\r\n");
        }
        //// Creates the file on server
        File.WriteAllText(FilePath, columnbind.ToString());
        string FileName = "test.csv";
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(FilePath);
        response.Flush();
        response.End();

        //// Deletes the file on server
        File.Delete(FilePath);

        //response.End();
        lblmsg.Text = "";
    }
    catch (Exception ex)
    {
        Console.Write(ex);
        Debug.Write(ex);
        lblmsg.Text = ex.Message;
        lblmsg.Style.Add("color", "#c73939");
    }
}

正确创建了csv但响应没有任何反应。代码执行但屏幕上根本没有任何内容。根据同样的其他几个问题,这就是解决方案。

1 个答案:

答案 0 :(得分:0)

尝试以下更改:

response.ContentType = "application/octet-stream";
response.AppendHeader("Content-Disposition","attachment; filename=" + Filename + ";");
response.TransmitFile( FilePath );
response.End();

请勿删除下一行中的文件,而应删除finally块中的文件:

catch (Exception ex)
{
    [..]
}
finally
{
    File.Delete(FilePath);
}