我在网上发现了这个CSV导出类,并希望从另一个类传递我自己的列表 我的列表已准备好并包含3列
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using System.IO;
using System.Reflection;
public class CsvExport<T> where T : class
{
public List<T> Objects;
public CsvExport(List<T> objects)
{
Objects = objects;
}
public string Export()
{
return Export(true);
}
public string Export(bool includeHeaderLine)
{
StringBuilder sb = new StringBuilder();
//Get properties using reflection.
IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
if (includeHeaderLine)
{
//add header line.
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(propertyInfo.Name).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
//add value for each property.
foreach (T obj in Objects)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
return sb.ToString();
}
//export to a file.
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
//export as binary data.
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
//get the csv value for field.
private string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
}
答案 0 :(得分:3)
以下是使用带样本类
的Exporter的示例class Sample
{
public string Field1 {get;set;}
public int Field2 {get;set;}
}
List<Sample> source = new List<Sample>()
// fill list
CsvExport<Sample> export = new CsvExport<Sample>(source);
export.ExportToFile("yourFile.csv");
所以基本上创建CsvExport<YourClass>
和现有对象的路径列表
答案 1 :(得分:3)
如果你想要帮助使用课程,那么我会说你需要做这样的事情。
为您的数据创建一个类..
public class MyData
{
public string Column1Data {get;set;}
public string Column2Data {get;set;}
public string Column3Data {get;set;}
}
将类型MyData的List传递到您的CsvExport类中,就像这样...
List<MyData> list = new List<MyData>();
//populate the list here
CsvExport<MyData> export = new CsvExport<MyData>();
export.ExportToFile(@"C:\MyExportFile.txt");
你现在应该有一个输出文件,如...
Column1Data,Column2Data,Column3Data
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
r3c1,r1c2,r3c3
要使用不同的输入类,只需将MyData引用切换为您所谓的类