在ASP中下载大型CSV文件.. NET MVC项目

本文关键字:文件 NET MVC 项目 CSV 大型 ASP 下载 | 更新日期: 2023-09-27 18:12:35

我需要导出一个非常大的csv文件(~100MB)。在互联网上,我发现了一个类似的代码,并为我的情况实现了它:

public class CSVExporter
{
    public static void WriteToCSV(List<Person> personList)
    {
        string attachment = "attachment; filename=PersonList.csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        WriteColumnName();
        foreach (Person person in personList)
        {
            WriteUserInfo(person);
        }
        HttpContext.Current.Response.End();
    }
    private static void WriteUserInfo(Person person)
    {
        StringBuilder stringBuilder = new StringBuilder();
        AddComma(person.Name, stringBuilder);
        AddComma(person.Family, stringBuilder);
        AddComma(person.Age.ToString(), stringBuilder);
        AddComma(string.Format("{0:C2}", person.Salary), stringBuilder);
        HttpContext.Current.Response.Write(stringBuilder.ToString());
        HttpContext.Current.Response.Write(Environment.NewLine);
    }
    private static void AddComma(string value, StringBuilder stringBuilder)
    {
        stringBuilder.Append(value.Replace(',', ' '));
        stringBuilder.Append(", ");
    }
    private static void WriteColumnName()
    {
        string columnNames = "Name, Family, Age, Salary";
        HttpContext.Current.Response.Write(columnNames);
        HttpContext.Current.Response.Write(Environment.NewLine);
    }
}

问题是我想在(!)整个CSV构建之前开始下载。为什么它不像我想象的那样工作,我必须改变什么?

在ASP中下载大型CSV文件.. NET MVC项目

可以使用

强制将响应刷新到客户端
Response.Flush();

在每个记录后面附加到流。详细信息请参考本文:

http://support.microsoft.com/kb/812406