我们正在将批量数据导出到我们的某个项目的csv文件中。所以在这种情况下,我们必须输出像a,b,c,d这样的值,这些值都必须保留在一列中。但是逗号会将它们分成不同的列。
如果我们导出一些在textarea中输入的值,或者包含\ r \ n等字符的编辑器将导出为csv中的单独行。我怎样才能解决这个问题?
答案 0 :(得分:59)
// CSV rules: http://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules
// From the rules:
// 1. if the data has quote, escape the quote in the data
// 2. if the data contains the delimiter (in our case ','), double-quote it
// 3. if the data contains the new-line, double-quote it.
if (data.Contains("\""))
{
data = data.Replace("\"", "\"\"");
}
if (data.Contains(","))
{
data = String.Format("\"{0}\"", data);
}
if (data.Contains(System.Environment.NewLine))
{
data = String.Format("\"{0}\"", data);
}
数据可以是来自db的单个项目,也可以是类型的属性值。
答案 1 :(得分:6)
处理此问题的最常用方法是使用"" around字段,但根据使用文件的人,可以通过多种方式处理。您可以分隔逗号,可以将逗号更改为特殊值或使用不同的分隔符,但命令最多