写入 CSV 文件并导出? [英] Write to CSV file and export it?

查看:37
本文介绍了写入 CSV 文件并导出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# ASP.net 中,有人可以告诉我如何将数组/列表中的条目写入服务器上的 CSV 文件,然后打开该文件吗?我认为第二部分类似于 - Response.Redirect("http://myserver.com/file.csv"),但不确定如何在服务器上写入文件.

In C# ASP.net, could someone show me how I can write entries from an Array/List to a CSV file on the server and then open the file? I think the second part would be something like - Response.Redirect("http://myserver.com/file.csv"), however not sure on how to write the file on the server.

另外,如果这个页面被很多用户访问,是每次生成一个新的CSV文件还是覆盖同一个文件更好?如果两个用户都尝试访问同一个 CSV 文件等,会不会有任何读/写/锁定问题?

Also if this page is accessed by many users, is it better to generate a new CSV file every time or overwrite the same file? Would there be any read/write/lock issues if both users try accessing the same CSV file etc.?

更新:

这可能是一个愚蠢的问题,我在 Google 上进行了搜索,但我找不到明确的答案 - 如何将 CSV 文件写入网络服务器并将其导出到 C# ASP.net 中?我知道如何生成它,但我想将它保存到 www.mysite.com/my.csv,然后将其导出.

This is probably a silly question and I have searched on Google but I'm not able to find a definitive answer - how do you write a CSV file to the webserver and export it in C# ASP.net? I know how to generate it but I would like to save it to www.mysite.com/my.csv and then export it.

推荐答案

罗姆,你做错了.您不想将文件写入磁盘以便 IIS 可以为它们提供服务.这增加了安全隐患并增加了复杂性.您真正需要做的就是将 CSV 直接保存到响应流中.

Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.

场景如下:用户希望下载 csv.用户提交一个表单,其中包含有关他们想要的 csv 的详细信息.您准备 csv,然后向用户提供一个指向 aspx 页面的 URL,该页面可用于构建 csv 文件并将其写入响应流.用户点击链接.aspx页面是空白的;在页面代码隐藏中,您只需将 csv 写入响应流并结束它.

Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.

您可以将以下内容添加到(我认为这是正确的)加载 事件:

You can add the following to the (I believe this is correct) Load event:

string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");

var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
  sb.AppendLine(TransformDataLineIntoCsv(line));

HttpContext.Current.Response.Write(sb.ToString());

写入响应流代码从这里开始一>.

这篇关于写入 CSV 文件并导出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆