2

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 need 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?

ProfK
  • 49,207
  • 121
  • 399
  • 775

4 Answers4

4

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");
     }
}
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
3

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

orcy
  • 1,304
  • 14
  • 29
2

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

Wyatt Barnett
  • 15,573
  • 3
  • 34
  • 53
2

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

Marcos Meli
  • 3,468
  • 24
  • 29
Omu
  • 69,856
  • 92
  • 277
  • 407