这是一段可解决此问题的代码。但请注意,您可以使用Web API并创建CSV格式化程序(并禁用输出缓冲)或直接使用pushtreamcontent。
对于MVC这里是一个示例代码,注意这个示例使用的是闭包,但您可以使用相同的IEnumerable。关键是让评估懒惰,所以你不要在内存中创建整个字符串。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace SampleApplication
{
public class HomeController : Controller
{
public ActionResult LargeCsv()
{
// TODO: Replace the func with real data access, or alternatively use an IQueryable/IEnumerable/IEnumerator implementation
// to access the data dynamically.
int i = 0;
Func<string> func =() =>
{
while (i < 100)
{
i++;
return "Name" + i + ", " + i;
}
return null;
};
return new CsvActionResult(func);
}
}
public class CsvActionResult : ActionResult
{
private readonly Func<string> _getNextCsvLine;
public CsvActionResult(Func<string> getNextCsvLine)
{
_getNextCsvLine = getNextCsvLine;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Headers.Add("Content-Type", "text/csv");
context.HttpContext.Response.BufferOutput = false;
// StreamWriter has inherent buffering so this operation is reasonably performant, it
// is going to write buffers to the wire rather than each writeline.
using (StreamWriter sw = new StreamWriter(context.HttpContext.Response.OutputStream))
{
string csvLine;
do
{
csvLine = _getNextCsvLine();
sw.WriteLine(csvLine);
} while (csvLine != null);
}
}
}
}
你可以用'Response.Write'在MVC太 – Rhumborl 2014-09-25 06:56:03
你可以让你的报表生成异步并通知用户这是完成后(给他发电子邮件或显示网址,在那里他可以下载的文件)。 – 2014-09-25 07:18:20