[英]Large CSV file download in ASP.NET MVC project
I need to export a really large csv file(~100MB). 我需要导出一个非常大的csv文件(~100MB)。 On the internet I found a similar code and implemented it for my case:
在互联网上,我找到了类似的代码并为我的案例实现了它:
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);
}
}
The problem is I want to start the download before(!) the whole CSV is constructed. 问题是我想在(!)构建整个CSV之前开始下载。 Why is not it working like I suppose it too and what must I change?
为什么它不像我想的那样工作,我必须改变什么?
You could probably force the response to be flushed to the client by using 您可以通过使用强制将响应刷新到客户端
Response.Flush();
after each record is appended to the stream. 将每条记录附加到流后。 Please refer to this article for more details:
有关更多详细信息,请参阅此文章:
http://support.microsoft.com/kb/812406 http://support.microsoft.com/kb/812406
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.