Ant P
Ant P

Reputation: 25221

Dynamic CSV file download

In an MVC project, I have an ActionLink, which, when clicked, should take an arbitrary number of objects associated with the user (supplied as a List), dynamically build a CSV file of the objects' attributes and prompt a download. The file shouldn't persist on the server, so it either needs to be removed after download or the download needs to come from a stream or similar. What's the neatest way of going about this? I've seen examples of this which manually compile a CSV string and use HttpResponse.Write(String) within the controller, but is this best practice?

Upvotes: 2

Views: 6670

Answers (4)

Brandon
Brandon

Reputation: 993

I have a function that is similar to this. I'm sure there is a "better" way to automatically find each of the members of the User object you pass it, but this way works.

    public ActionResult ExportCSV(List<User> input)
    {
        using (MemoryStream output = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(output, Encoding.UTF8))
            {
                foreach (User user in input)
                {
                    writer.Write(user.firstattribute);
                    writer.Write(",");
                    writer.Write(user.secondattribute);
                    writer.Write(",");
                    writer.Write(user.thirdattribute);
                    writer.Write(",");
                    writer.Write(user.lastattribute);
                    writer.WriteLine();
                }

                writer.Flush();
            }

            output.Position = 0;

            return Controller.File(output, "text/comma-separated-values", "report.csv");
        }
    }

Upvotes: 4

Jacob
Jacob

Reputation: 78840

LINQ to CSV is reportedly a nice library for generating CSV content. Once you generate your CSV, use the File method of Controller to return a FileStreamResult from your action; that lets you send any arbitrary stream as a response, whether it's a FileStreamResult or any other type of Stream.

Upvotes: 0

David
David

Reputation: 218827

If you have the stream, returning a FileStreamResult is probably the "cleanest" way to do it in ASP.NET MVC.

Upvotes: 3

SLaks
SLaks

Reputation: 887453

You should manually assemble a string, then return Content(str, "text/csv");

Upvotes: 0

Related Questions