开发者

How can I export to CSV in an ASP.NET MVC application?

开发者 https://www.devze.com 2023-01-12 14:39 出处:网络
I know this question has been asked and answered in several ways, but none of them get to the crux of the matter that I n开发者_如何学Goeed to understand.In WebForms, we \'subvert\' the rendering proc

I know this question has been asked and answered in several ways, but none of them get to the crux of the matter that I n开发者_如何学Goeed to understand. In WebForms, we 'subvert' the rendering process and write straight to the Response's output stream. How does one achieve that using a Controller Action, to write CSV to a file for Excel?


Just to elaborate on Omu's FileHelpers answer, I was able to combine @shamp00's ideas here with this answer here in order to render a CSV to a FileContentResult via stream on the fly.

Given a FileHelpers DTO Model like so:

[DelimitedRecord(",")] 
public class Foo
{
    public string Name { get; set; }
    public int Id { get; set; }
}

And a controller action:

public FileContentResult DownloadFoosCSV()
{
     var foos = GetFoos(); // IEnumerable<Foo>

     var fileHelper = new FileHelperEngine<Foo>();
     using (var stream = new MemoryStream())
     using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
     {
         fileHelper.WriteStream(streamWriter, foos);
         streamWriter.Flush();
         return File(stream.ToArray(), "application/csv", "NewFoos.csv");
     }
}


You can try CsvActionResult described at http://develoq.net/2011/export-csv-actionresult-for-asp-net-mvc/


Same way you'd write any other file -- use FileResult and it's descendants.


I've been using this: http://www.filehelpers.net/ in an asp.net mvc application, look at the getting started guide, you should get it from there

0

精彩评论

暂无评论...
验证码 换一张
取 消