Last active
October 18, 2019 19:34
-
-
Save hd9/c60c7f1cb89742dbe98e90c65ac40925 to your computer and use it in GitHub Desktop.
Export CSV generated in-memory from an Asp.Net controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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