Exporting from MVC View to CSV (for Excel)
This is a strange one, I have everything working but in the controller code below the fileStreamResult that comes up in the file has only 84 of 100 results. The variable searchResults contains 100 records.
If I step through the controller code at runtime the "sw.WriteLine(........." line inside the loop executes 100 times as expected.
So it appears that the data being sent to the fileStream is being truncated.
After debugging i've no idea why this is happening since all 100 records contain no nulls or any odd data with meta-characters or anything like that. Anyone ever seen this odd behaviour before or have any ideas on this?
My 开发者_如何学JAVAcontroller code :
public FileStreamResult Export(string searchText, string searchTextSite, string StartDate, string EndDate)
{
var searchResults = getSearchResults(searchText, searchTextSite, StartDate, EndDate);
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
var sw = new StreamWriter(new MemoryStream());
sw.WriteLine("\"Ref\",\"Source\",\"Collected\"");
foreach (var line in searchResults.ToList())
{
sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"",
line.WasteId,
line.SourceWasteTypeId.ToDescription(),
line.CollectedDate.ToShortDateString()));
}
sw.BaseStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(sw.BaseStream, "text/csv");
}
Does the stream need to be flushed before returning the result? Try sw.Flush();
before the Seek
精彩评论