public class CsvFileResult<T> : FileResult where T : class { private IEnumerable<T> _data; public CsvFileResult(IEnumerable<T> data) : base("text/CSV") { _data = data; } protected override void WriteFile(HttpResponseBase response) { var maxLine = int.Parse(ConfigurationManager.AppSettings["csvExport:MaxLine"]); int count = 0; var outPutStream = response.OutputStream; using (var streamWriter = new StreamWriter(outPutStream, System.Text.Encoding.UTF8)) using (var writer = new CsvWriter(streamWriter)) { writer.WriteHeader<T>(); foreach (var item in _data) { writer.WriteRecord(item); count++; if (count % 50 == 0) { streamWriter.Flush(); response.Flush(); } if (count >= maxLine) { break; } } } } }
实现依赖于CSVHelper
ASP.NET MVC 导出CSV 的 CsvFileResult 类
原文:http://blog.csdn.net/lan_liang/article/details/43678931