2013-04-05 39 views
2

我發現許多解決方案導出類CSV但我的問題是這樣的:出口類

我試圖出口類有一個屬性是一個ObservableCollection。例如:

public class ShipmentForExport 
    { 
     public string WaybillNumber { get; set; } 
     public DateTime WaybillDate { get; set; } 
     public string CustomerName { get; set; } 
     public string CustomerCode { get; set; } 
     public string CollectingBranchName { get; set; } 
     public string CollectingBranchCode { get; set; } 
     public string RecipientName { get; set; } 
     public string RecipientPhoneNumber { get; set; } 
     public string RecipientCellphoneNumber { get; set; } 
     public string RecipientCompany { get; set; } 
     public string DestinationAddress1 { get; set; } 
     public string DestinationAddress2 { get; set; } 
     public string DestinationCity { get; set; } 
     public string DestinationSuburb { get; set; } 
     public string DestinationProvince { get; set; } 
     public string DestinationCountry { get; set; } 
     public string DestinationPostalCode { get; set; } 

     ***public ObservableCollection<InHouseParcel> Parcels { get; set; }*** 

    } 

當我嘗試出口貨物清單到csv它的工作原理,但很明顯,包裹不出口,我希望他們的方式。

我嘗試過使用Filehelpers Library和csvHelper。

任何幫助非常感謝!

回答

0

使用CsvHelper(我保持一庫)...

寫作時,你就會有,因爲不支持集合屬性的寫作手工編寫。

foreach(var record in records) 
{ 
    csv.WriteField(record.WaybillNumber); 
    ... 
    foreach(var parcel in record.Parcels) 
    { 
     csv.WriteField(parcel); 
    } 
} 

閱讀是一個更容易一些,因爲你可以在映射添加。

Map(m => m.Parcels).ConvertUsing(row => 
{ 
    var oc = new ObservableCollection<InHouseParcel>(); 
    var parcel = row.GetField<InHouseParcel>(17); 
    oc.Add(parcel); 
}); 

你需要通過該行的其餘字段的字段值轉換成InHouseParcel和循環。我會把這個任務交給你。

0

喬希的答案現在已經過時了。你可以使用像一個類型轉換器:

CsvHelper.TypeConversion.TypeConverterFactory.AddConverter<ObservableCollection<string>>(new CsvHelper.TypeConversion.StringListConverter()); 

using (var txt = new StreamReader(filename)) 
using (var reader = new CsvHelper.CsvReader(txt)) 
{ .... } 



namespace CsvHelper.TypeConversion 
{ 
public sealed class StringListConverter : DefaultTypeConverter 
{ 
    public override object ConvertFromString(TypeConverterOptions options, string text) 
    { 
     var oc = new ObservableCollection<string>(); 
     if (text.IndexOf('|') >= 0) 
     { 
      var list = text.Split('|').ToList<string>();// base.ConvertFromString(options, text); 
      oc = new ObservableCollection<string>(list); 
     } 
     return oc; 
    } 

    public override string ConvertToString(TypeConverterOptions options, object value) 
    { 
     var l = value as IEnumerable<string>; 
     if (l == null || l.Count() == 0) 
     { 
      return ""; 
     } 

     return string.Join("|", l); 
    } 

    public override bool CanConvertFrom(Type type) 
    { 
     return type == typeof(string); 
    } 
} 

}