0
是否有更簡單的方法將telerik orm實體列表轉換爲csv格式?如何將Telerik ORM實體列表轉換爲csv文件
是否有更簡單的方法將telerik orm實體列表轉換爲csv格式?如何將Telerik ORM實體列表轉換爲csv文件
以下簡單的靜態類將幫助您完成此任務。請注意,它會創建一個.csv文件,其中包含實體屬性的值,而不考慮到導航屬性:
public static partial class EntitiesExporter
{
public static void ExportEntityList<T>(string fileLocation, IEnumerable<T> entityList, string seperator = " , ")
{
string content = CreateFileContent<T>(entityList, seperator);
SaveContentToFile(fileLocation, content);
}
private static string CreateFileContent<T>(IEnumerable<T> entityList, string seperator)
{
StringBuilder result = new StringBuilder();
List<PropertyInfo> properties = new List<PropertyInfo>();
foreach (PropertyInfo item in typeof(T).GetProperties())
{
if (item.CanWrite)
{
properties.Add(item);
}
}
foreach (T row in entityList)
{
var values = properties.Select(p => p.GetValue(row, null));
var line = string.Join(seperator, values);
result.AppendLine(line);
}
return result.ToString();
}
private static void SaveContentToFile(string fileLocation, string content)
{
using (StreamWriter writer = File.CreateText(fileLocation))
{
writer.Write(content);
writer.Close();
}
}
}
可以消耗這樣的類代碼:
using (EntitiesModel dbContext = new EntitiesModel())
{
IQueryable<Category> cats = dbContext.Categories;
string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string fileLocation = Path.Combine(appDir, "test.csv");
EntitiesExporter.ExportEntityList<Category>(fileLocation, cats);
}
我希望這有助於。
http://stackoverflow.com/questions/17698228/generic-list-to-csv-string – Sajeetharan