我有两种使用.net MVC导出CSV文件的解决方案,它们使用名为CsvHelper的NuGet包。
这两种解决方案的工作结果相同,但是我很好奇,哪种方法能更好地利用CPU,内存和磁盘io?
CsvHelper有一个帮手
public static void GenerateCsv<T>(Stream stream, IEnumerable<T> data)
{
using (var sw = new StreamWriter(stream, Encoding.UTF8))
using (var writer = new CsvWriter(sw))
{
writer.WriteRecords(data);
}
}
public static byte[] WriteCsvToMemory<T>(IEnumerable<T> data)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteRecords(data);
streamWriter.Flush();
return memoryStream.ToArray();
}
}
使用响应方式的第一个解决方案
public void ExportDemoCsv()
{
var data = new List<Test>();
var fileName = "exportExample.csv";
Response.AppendHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentType = "text/csv";
Response.ContentEncoding = Encoding.UTF8;
Core.Helpers.CsvHelper.GenerateCsv(Response.OutputStream, data);
}
使用FileContentResult的第二个解决方案,并从助手中获取byte []
public ActionResult ExportDemoCsv()
{
var data = new List<Test>();
var csvByte = Core.Helpers.CsvHelper.WriteCsvToMemory(data);
return File(csvByte, "text/csv", "exportExample.csv");
}
找到一种方法来思考这种问题以及如何证明两种解决方案只是一个问题
使用异步是一个好主意,但是我怎么知道它的好处。
更新: 我写了异步模式
public static async Task<byte[]> WriteCsvToMemory<T>(IEnumerable<T> data)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
using (var csvWriter = new CsvWriter(streamWriter))
{
foreach (var record in data)
{
csvWriter.WriteRecord(record);
await csvWriter.NextRecordAsync();
}
await streamWriter.FlushAsync();
return memoryStream.ToArray();
}
}
答案 0 :(得分:2)
关于@Christian Sauer的评论,这是一个异步版本。
public static async Task GenerateCsv<T>(Stream stream, IEnumerable<T> data)
{
using (var sw = new StreamWriter(stream, Encoding.UTF8))
using (var writer = new CsvWriter(sw))
{
foreach (var record in data)
{
writer.WriteRecord(record);
await writer.NextRecordAsync();
}
}
}