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

查看:191
本文介绍了写入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文件或覆盖同一个文件?

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.?

更新:如果两个用户尝试访问同一个CSV文件,

Update:

这可能是一个愚蠢的问题,我已在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,然后为用户提供一个URL到一个aspx页面,可以用来构造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());

写入响应流代码从这里ganked

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

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