0

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?

1
  • Sure, you can just return it verbatim, and set the content-type of the response to text/csv. Commented Jul 21, 2019 at 10:52

1 Answer 1

1

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");
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have a question. I wonder if I could send the resulting csv as string? The thing is I want to return an object, inside this object I want to include the CSV string as well as other information. I tried ExecuteResult but could not get it work. Any help?
@renakre Can you ask that as a separate question, including any supporting details - that way the wider-community will see it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.