-1
这是我遇到的一个相当简单的问题,但我的知识非常有限。我有一个将现有数据库变成CSV的程序;但是,许多字段都包含逗号,我需要它们才能逃脱。我已经尝试了一些无用的东西(在ObjectToCsvData下),所以任何与包含片段的帮助将不胜感激。逗号在stringbuilder中逃脱
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
namespace OfaSort
{
public static class Utility
{
public static string CollectionToCsv(IList collection)
{
StringBuilder sb = new StringBuilder();
for (int index = 0; index < collection.Count; index++)
{
object item = collection[index];
if (index == 0)
{
sb.Append(ObjectToCsvHeader(item));
}
sb.Append(ObjectToCsvData(item));
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
public static string ObjectToCsvData(object obj)
{
/*if (obj == null)
{
throw new ArgumentNullException("obj", "value is null");
}*/
StringBuilder sb = new StringBuilder();
Type t = obj.GetType();
PropertyInfo[] pi = t.GetProperties();
for (int index = 0; index < pi.Length; index++)
{
/*object oTest = pi[index].GetValue(obj, null);
string str = oTest.ToString();
sb.Append(str.CsvQuote());
*/
sb.Append(pi[index].GetValue(obj, null));
if (index < pi.Length - 1)
{
sb.Append(",");
}
}
return sb.ToString();
}
public static string ObjectToCsvHeader(object obj)
{
/*if (obj == null)
{
throw new ArgumentNullException("obj", "value is null!");
}*/
StringBuilder sb = new StringBuilder();
Type t = obj.GetType();
PropertyInfo[] pi = t.GetProperties();
for (int index = 0; index < pi.Length; index++)
{
sb.Append(pi[index].Name);
if (index < pi.Length - 1)
{
sb.Append(",");
}
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
public static string CsvQuote(this string text)
{
if (text == null)
{
return string.Empty;
}
bool containsQuote = false;
bool containsComma = false;
int len = text.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = text[i];
if (ch == '"')
{
containsQuote = true;
}
else if (ch == ',')
{
containsComma = true;
}
}
bool mustQuote = containsComma || containsQuote;
if (containsQuote)
{
text = text.Replace("\"", "\"\"");
}
if (mustQuote)
{
return "\"" + text + "\"";
}
else
{
return text;
}
}
}
}
简单的测试:__if((VAL包含',')||(VAL包含' “'))__涡卷值在'”'和逃逸的任何现有'“' (如''“') – 2014-12-01 21:46:35
1.问题在哪里?2.不要编写自己的CSV编写器或解析器,这里有_many_工作库/ nugets – Mormegil 2014-12-01 21:48:08
您的containsQuote /逗号代码可以替换为'containsQuote = text.IndexOf(''')> = 0; containsComma = text.IndexOf(',')> = 0;'。 – 2014-12-01 21:55:37