2018年7月6日 星期五

[C#] 將集合物件轉成CSV

將集合物件轉成CSV字串

//將集合物件轉成CSV字串
public static string GeneratorCSV(IEnumerable data, bool hasColumn)
{
   StringBuilder sr = new StringBuilder();
   Type t = typeof(T);
   PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

   //是否要輸出屬性名稱
   if (hasColumn)
   {
      sr.AppendLine(string.Join(",", propInfos.Select(i => i.Name)));
   }

   foreach (var item in data)
   {
      sr.AppendLine(string.Join(",", propInfos.Select(i => i.GetValue(item))));
   }

   return sr.ToString();
}

將集合物件轉成CSV檔案

//將集合物件轉成CSV檔案
public static void GeneratorCSVFile(IEnumerable data, bool hasColumn, string FilePath)
{
   using (var file = new StreamWriter(FilePath))
   {
      Type t = typeof(T);
      PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                
      //是否要輸出屬性名稱
      if (hasColumn)
      {
         file.WriteLineAsync(string.Join(",", propInfos.Select(i => i.Name)));
      }

      foreach (var item in data)
      {
         file.WriteLineAsync(string.Join(",", propInfos.Select(i => i.GetValue(item))));
      }
   }
}

沒有留言:

張貼留言