這是一段可解決此問題的代碼。但請注意,您可以使用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