如何在 C# 中将所有值(属性)写入 csv 格式的字符串?例如:
class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);
现在我想要一个字符串“Kevin;Kline;33”
换句话说,我想将一个对象序列化为 CSV
var person = new Person("Kevin","Kline",33);
using (var csv = new CsvWriter(new StreamWriter("file.csv")))
{
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.Delimiter = ';';
csv.WriteRecord(person);
}
输出:
Kevin;Kline;33
通过使用反射,您可以从对象中检索属性信息
foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
if (prp.CanRead) {
object value = prp.GetValue(obj, null);
string s = value == null ? "" : value.ToString();
string name = prp.Name;
...
}
}
该GetProperties
方法有一个重载接受BindingFlags
,通过它您可以确定您需要哪种属性,例如私有/公共实例/静态。
你可以像这样组合它们
var properties = type.GetProperties(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
应用于你的问题,你可以写
List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();
// First line contains field names
foreach (PropertyInfo prp in properties) {
if (prp.CanRead) {
sb.Append(prp.Name).Append(';');
}
}
sb.Length--; // Remove last ";"
sb.AppendLine();
foreach (Person person in people) {
foreach (PropertyInfo prp in properties) {
if (prp.CanRead) {
sb.Append(prp.GetValue(person, null)).Append(';');
}
}
sb.Length--; // Remove last ";"
sb.AppendLine();
}
File.AppendAllText("C:\Data\Persons.csv", sb.ToString());
将字符串括在双引号中并通过加倍它们来转义它们包含的双引号也是一个好主意。
你可以使用这样的东西:
...
PropertyInfo[] properties = obj.GetType().GetProperties();
string CSVRow = "";
foreach (PropertyInfo pi in properties)
{
CSVRow = CSVRow + pi.GetValue(obj, null) + ";";
}
CSVRow.Remove(CSVRow.Length - 1, 1);
...
我相信FileHelpers对此有好处,但我自己并没有在愤怒中使用它
像这样的东西:
public string ToCsv()
{
return string.Join(";", new string[]{
_firstName,
_lastName,
_age.ToString()
}.Select(str=>Escape(str)));
}
或者,使用反射,
public static string ToCsv(this object obj)
{
return string.Join(";",
this.GetType().GetProperties().Select(pi=>
Escape(pi.GetValue(this, null).ToString())
));
}
其中 Escape 是一个适当的转义函数。
一种可能的实现,它读取复杂对象(深度对象序列化),例如具有对象数组属性的对象数组,并保存格式为 CSV 文件的 oa 字符串:
private string ToCsv(string separator, IEnumerable<object> objectList)
{
StringBuilder csvData = new StringBuilder();
foreach (var obj in objectList)
{
csvData.AppendLine(ToCsvFields(separator, obj));
}
return csvData.ToString();
}
private string ToCsvFields(string separator, object obj)
{
var fields = obj.GetType().GetProperties();
StringBuilder line = new StringBuilder();
if (obj is string)
{
line.Append(obj as string);
return line.ToString();
}
foreach (var field in fields)
{
var value = field.GetValue(obj);
var fieldType = field.GetValue(obj).GetType();
if (line.Length > 0)
{
line.Append(separator);
}
if (value == null)
{
line.Append("NULL");
}
if (value is string)
{
line.Append(value as string);
}
if (typeof(IEnumerable).IsAssignableFrom(fieldType))
{
var objectList = value as IEnumerable;
StringBuilder row = new StringBuilder();
foreach (var item in objectList)
{
if (row.Length > 0)
{
row.Append(separator);
}
row.Append(ToCsvFields(separator, item));
}
line.Append(row.ToString());
}
else
{
line.Append(value.ToString());
}
}
return line.ToString();
}