[英]Write to CSV file and export it?
在C#ASP.net中,有人可以告诉我如何将数组/列表中的条目写入服务器上的CSV文件,然后打开文件吗? 我认为第二部分将是 - Response.Redirect(“ http://myserver.com/file.csv ”),但不确定如何在服务器上写入文件。
此外,如果许多用户访问此页面,是否每次生成新的CSV文件或覆盖同一文件更好? 如果两个用户都尝试访问相同的CSV文件等,是否会出现读/写/锁定问题?
更新:
这可能是一个愚蠢的问题,我在Google上搜索过,但我无法找到明确的答案 - 你如何将CSV文件写入网络服务器并将其导出到C#ASP.net? 我知道如何生成它,但我想将其保存到www.mysite.com/my.csv然后导出它。
罗姆,你做错了。 您不希望将文件写入磁盘,以便IIS可以为它们提供服务。 这增加了安全隐患并增加了复杂性。 您真正需要做的就是将CSV直接保存到响应流中。
这是场景:用户希望下载csv。 用户提交一个表单,其中包含有关他们想要的csv的详细信息。 您准备csv,然后向用户提供一个aspx页面的URL,该页面可用于构造csv文件并将其写入响应流。 用户单击该链接。 aspx页面是空白的; 在页面代码隐藏中,您只需将csv写入响应流并结束它。
您可以添加以下内容(我相信这是正确的) 加载事件:
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());
写入响应流代码从这里开始 。
这是一个非常简单的C#免费开源CsvExport类。 底部有一个ASP.NET MVC示例。
https://github.com/jitbit/CsvExport
它关注换行符,逗号,转义引号,MS Excel兼容性...只需将一个简短的.cs
文件添加到您的项目中,您就可以开始了。
(免责声明:我是贡献者之一)
关于Will的答案的评论,你可能想要替换HttpContext.Current.Response.End();
使用HttpContext.Current.ApplicationInstance.CompleteRequest();
原因是Response.End()
抛出System.Threading.ThreadAbortException
。 它中止一个线程。 如果你有一个异常记录器,那么它将充满ThreadAbortExceptions,在这种情况下是预期的行为。
直观地说,将CSV文件发送到浏览器不应引发异常。
在这里查看更多是否Response.End()被认为是有害的?
这是我写的一个CSV动作结果,它采用DataTable并将其转换为CSV。 您可以从视图中返回此内容,它将提示用户下载该文件。 您应该能够轻松地将其转换为List兼容表单,甚至只需将列表放入DataTable即可。
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
namespace Detectent.Analyze.ActionResults
{
public class CSVResult : ActionResult
{
/// <summary>
/// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
/// </summary>
/// <param name="dataTable"></param>
/// <param name="fileName">The full file name including the extension.</param>
public CSVResult(DataTable dataTable, string fileName)
{
Table = dataTable;
FileName = fileName;
}
public string FileName { get; protected set; }
public DataTable Table { get; protected set; }
public override void ExecuteResult(ControllerContext context)
{
StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);
for (int c = 0; c < Table.Columns.Count; c++)
{
if (c > 0)
csv.Append(",");
DataColumn dc = Table.Columns[c];
string columnTitleCleaned = CleanCSVString(dc.ColumnName);
csv.Append(columnTitleCleaned);
}
csv.Append(Environment.NewLine);
foreach (DataRow dr in Table.Rows)
{
StringBuilder csvRow = new StringBuilder();
for(int c = 0; c < Table.Columns.Count; c++)
{
if(c != 0)
csvRow.Append(",");
object columnValue = dr[c];
if (columnValue == null)
csvRow.Append("");
else
{
string columnStringValue = columnValue.ToString();
string cleanedColumnValue = CleanCSVString(columnStringValue);
if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
{
cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
}
csvRow.Append(cleanedColumnValue);
}
}
csv.AppendLine(csvRow.ToString());
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
response.Write(csv.ToString());
}
protected string CleanCSVString(string input)
{
string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
return output;
}
}
}
如何写入文件(在Google中轻松搜索)... 第一个搜索结果
至于每次用户访问页面时创建文件......每次访问都将代表自己的行为。 您的业务案例将决定行为。
案例1 - 相同的文件但不会改变(这种类型的案例可以有多种方式被定义)
案例2 - 每个用户都需要生成自己的文件
案例3 - 每个访问都需要生成相同的文件
查看http://www.codeproject.com/KB/cs/CsvReaderAndWriter.aspx上的 csvreader / writer库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.