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
时间: 2024-10-24 00:55:33