Reputation: 8291
I have the following code to convert the EF output to CSV file (and save it to the server side and then return it):
List<LearningActionMonitoringDTO> results = _context
.LearningActionProgressUpdates
.Include(la => la.LearningAction)
.Where(la => la.LearningActionId == actionId)
.Select(la => new LearningActionMonitoringDTO
{
Title = la.LearningAction.Title,
Progress = la.Progress,
ProgressDate = la.DateCreated.ToString("g"),
}).ToList();
using (var csv = new CsvWriter(new StreamWriter("CSVfiles/Actors.csv")))
{
csv.WriteRecords(results);
}
FileInfo f = new FileInfo("CSVfiles/Actors.csv");
return f;
I wonder if I could return the results
in CSV format without first saving it to the server. I need the data in CSV file to feed into a React component for creating some charts. Any help?
Upvotes: 0
Views: 580
Reputation: 38820
Based on my comment, and some code from the author of CsvWriter
(assuming it's the same CSV library), to write it to a string, you do the following:
using( var stream = new MemoryStream() )
using( var reader = new StreamReader( stream ) )
using( var writer = new StreamWriter( stream ) )
using( var csv = new CsvWriter( writer ) )
{
csv.WriteRecords( results);
writer.Flush();
stream.Position = 0;
var text = reader.ReadToEnd();
}
(From here)
Now that you have your CSV file as a chunk of text, we can return it from a Controller thusly:
public ActionResult DownloadCSV()
{
return Content(yourCsvString, "text/csv");
}
Upvotes: 1