Skip to content

Instantly share code, notes, and snippets.

@hd9
Last active October 18, 2019 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hd9/c60c7f1cb89742dbe98e90c65ac40925 to your computer and use it in GitHub Desktop.
Save hd9/c60c7f1cb89742dbe98e90c65ac40925 to your computer and use it in GitHub Desktop.
Export CSV generated in-memory from an Asp.Net controller
// Export CSV generated in-memory from an Asp.Net controller
// Source: https://blog.hildenco.com/2018/03/exporting-csv-generated-in-memory-in.html
public class MyController : Controller
{
public void DownloadReport(string id)
{
var rptLines = new List<CsvLine>();
var count = 0;
// load your data from the db...
// example: using RavenDB
using (var session = store.OpenSession())
{
var results = session.Query<BatchRow>("BatchIndex").ToList();
rptLines = results.ConvertAll(bl => new CsvLine(bl.RefId, bl.Name, bl.Description /*, etc */ ));
}
// init StringWriter, StringBuilder
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
// init CsvWriter
var csv = new CsvWriter(sw);
// write all rptLines records to my StringBuilder
csv.WriteRecords(rptLines);
}
// respond with data
Response.ContentType = "application/csv";
Response.AddHeader("content-disposition", @"attachment;filename=""export.csv"""); //necessary to return a 'filename' to the user
Response.Write(sb.ToString());
Response.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment