gpt4 book ai didi

c# - 使用包含逗号的数据写入 MVC 中的 csv

转载 作者:行者123 更新时间:2023-11-30 12:13:49 25 4
gpt4 key购买 nike

我的一个 Action 输出一个 csv 文件。问题是如果一个字段包含逗号,那么它会将数据行拆分为两个字段。我尝试使用“\””将每一行包含在双引号中,但这不起作用。有人可以指导我正确的方向吗?

更新

var sw = new StringWriter();
sw.WriteLine(String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}", "First Name","Last Name","Address1","Address2","City","State","Postal Code","Country","Dealer ID","Dealer Name","Survey Source","Amount","Email","Survey Code"));
sw.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"", model.SurveyWinnerDetails.Select(p => p.FirstName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.LastName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Address1).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Address2).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.City).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.State).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.PostalCode).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.CountryCode).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.DealerID).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.DealerName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.SurveySource).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Amount).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Email).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.SurveyCode).First().Replace("\"", "\"\"")));
return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "text/csv", "SurveyWinner.csv");

当我现在运行它时,我得到一个错误:对象引用未设置到对象的实例。

最佳答案

CSV 文件使用与 C# 不同的转义。如果要在 CSV 文件中包含逗号,则需要用双引号将整个单元格转义。应该注意的是,这会产生在文本中放置双引号的次要问题!将双引号加倍可以避免此问题。

即。此 csv 文件将显示为包含 3 列的单行:

This is a single cell,"This,is,a,single,cell", "This,is""a,single""cell"

尝试这样的事情:

sw.WriteLine(string.Format("\"{0}\",\"{0}\"", model.MyStringData1.Replace("\"", "\"\""));

请特别注意,表示单元格的双引号紧跟在逗号之后,而在您的示例中您有一个额外的空格。您需要删除这个额外的空间才能正确转义您的 CSV 数据。

关于c# - 使用包含逗号的数据写入 MVC 中的 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11001322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com