4

我的一项操作输出了一个 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");

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

4

2 回答 2

2

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

IE。此 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 数据。

于 2012-06-12T17:22:55.053 回答
1

没有一种“官方”CSV 格式,但最常见的格式在 RFC 4180 (http://tools.ietf.org/html/rfc4180) 中有概述。根据该 RFC(第 6 节),包含逗号的字段应该用双引号引起来。

根据@Axam 在下面的观察,RFC 4180 不允许逗号周围有额外的空格。将格式字符串更改为:

"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}"
于 2012-06-12T17:12:21.817 回答