简体   繁体   English

动态CSV文件下载

[英]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. 在MVC项目中,我有一个ActionLink,单击该链接时,它应该获取与用户关联的任意数量的对象(作为列表提供),动态构建对象属性的CSV文件并提示下载。 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? 我已经看到了手动编译CSV字符串并在控制器内使用HttpResponse.Write(String)示例,但这是最佳实践吗?

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. 我敢肯定,有一种“更好”的方法可以自动找到传递给它的User对象的每个成员,但是这种方法有效。

    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");
        }
    }

如果有流,则在ASP.NET MVC中返回FileStreamResult可能是“最干净”的方法。

您应该手动组装一个字符串,然后return Content(str, "text/csv");

LINQ to CSV is reportedly a nice library for generating CSV content. 据说LINQ to CSV是一个很好的库,用于生成CSV内容。 Once you generate your CSV, use the File method of Controller to return a FileStreamResult from your action; 生成CSV后,请使用ControllerFile方法从操作中返回FileStreamResult that lets you send any arbitrary stream as a response, whether it's a FileStreamResult or any other type of Stream . 它使您可以发送任意流作为响应,无论是FileStreamResult还是任何其他类型的Stream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM