2013-06-29 50 views
0

我需要幫助使用LINQ將數據導出到Excel。我從linq獲得了數據,但不知道如何導出數據。我的代碼如下導出結果集從LINQ到SQL擅長

using (DataClassesDataContext dc = new DataClassesDataContext()) 
    { 
     foreach (var mt in dc.Mapping.GetTables()) 
     { 
      string sql = String.Format("Select * from {0} where ID = {1} ", mt.TableName, TenantID); 
      var data = dc.ExecuteQuery(mt.RowType.Type, sql); 
      //data is here now. 
      string path = "D:\\CSvFiles\\"; 
      if (!System.IO.Directory.Exists(path)) 
       System.IO.Directory.CreateDirectory(path); 

      path = path + mt.TableName + ".csv"; 
      foreach (var item in data) 
      { 
       System.IO.File.WriteAllText(path, item.ToString()); 

      } 
     } 
    } 

回答

0

試試這個:

using (DataClassesDataContext dc = new DataClassesDataContext()) 
    { 
     foreach (var mt in dc.Mapping.GetTables()) 
     { 
      string sql = String.Format("Select columnName from {0} where ID = {1} ", mt.TableName, TenantID); 
      var data = dc.ExecuteQuery(mt.RowType.Type, sql).ToArray(); 
      //data is here now. 
      string path = "D:\\CSvFiles\\"; 
      if (!System.IO.Directory.Exists(path)) 
       System.IO.Directory.CreateDirectory(path); 

      path += mt.TableName + ".csv"; 
      System.IO.File.WriteAllText(path, String.Join(",",data)); 
     } 
    } 
+0

如果映射行類型是說'Customer',不會'Join'使用塔'Customer'對象的'ToString' - - 類似於「MyApp.Customer」的東西?在這種情況下,生成的字符串看起來像「MyApp.Customer,MyApp.Customer,MyApp.Customer」。 –

+0

感謝您的建議,但這不適合我。 – Mohit