jaabh
jaabh

Reputation: 1004

Writing and downloading a csv file using linq methods in c# is returning wrong data

In ASP.NET Core, I am using a Linq method to get my data from my Prescriptions table from the database, I am attempting to write that data to a csv file called FutureFills.csv in wwwroot, and download that file. Here is the controller

[HttpGet]
[Route("~/FutureFills")]
[Produces("text/csv")]
public IActionResult ExportFile()
{

    var futurefills = _context.Prescriptions
      .Where(f => f.FolderStatusId == 9)
      .Where(d => d.DeliveryDate == DateTime.Today.AddDays(1))
      .ToList();

    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    System.IO.StreamWriter write = new System.IO.StreamWriter(Stream);

    CsvFileDescription file = new CsvFileDescription 
    { 
        SeparatorChar = ',', FirstLineHasColumnNames = true 
    };

    return File(System.Text.Encoding.ASCII.GetBytes(futurefills.ToString()), "text/csv", "FutureFills.csv");
}

So I have a button on a page that calls this action and downloads a csv file, it downloads and seems to work but when I open the csv file it is not the data that I need, I am expecting to get the Prescriptions table from my database, however I get this in the csv file

enter image description here

What am I doing wrong that it is not writing the correct data into the file?

Upvotes: 0

Views: 749

Answers (2)

user191152
user191152

Reputation:

It seems that you are simply outputting futurefills.ToString(), which is just outputting the name of the type of object it is holding.

Are you certain that futurefills.ToString() holds the value you are expecting ? Try debugging your application, and inpect the value of futurefills after the Linq-query.

You need to iterate over each element in the futureFills object, that you have seen contains to items. So you need to write a construct similar to this:

var output = new StringBuilder();
foreach (var row in futurefills)
{
    output.AppendLine(row.Field1 + ", " + row.Field2);
}

And then you can go ahead and output.ToString()

Something like this:

return File(System.Text.Encoding.ASCII.GetBytes(output.ToString()), "text/csv", "FutureFills.csv");

Upvotes: 2

Mark C.
Mark C.

Reputation: 6460

You never executed the query. Add a .ToList() to the end of futureFills

    var futurefills = _context.Prescriptions
      .Where(f => f.FolderStatusId == 9)
      .Where(d => d.DeliveryDate == DateTime.Today.AddDays(1)).ToList();

Upvotes: 1

Related Questions