【发布时间】:2011-10-28 13:44:10
【问题描述】:
我需要导出一个非常大的 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 之前(!)开始下载。为什么它不像我想的那样工作,我必须改变什么?
【问题讨论】:
-
两个快速 cmets:传入一个 IEnumerable
并避免预先填充列表(对于 100MB 的输出,它很可能有很多条目),并且每 1000 行左右刷新一次响应输出. -
@Morten Mertner,是的,谢谢,我已经这样做了,这是我基于代码找到的示例
-
我很好奇你把它放在你的 MVC 框架的什么地方?您是否刚刚从操作中调用了 WriteToCSV() 方法?
-
如果解决了,能否提供最终代码?
标签: c# http csv large-files