2009-07-11 44 views
1

我給出的問題如下:如何使用dataTable?

我有一個x列的對象,每列都有y值。現在我必須把它帶入Excel。

我發現了一個可以輕鬆導出數據表的代碼片段。所以我會把我的對象帶到數據表中。我怎樣才能做到這一點?

語言是C#

+0

什麼編程語言? – 2009-07-11 11:47:56

+0

C#.Net抱歉.............. – Kovu 2009-07-11 11:51:44

回答

4

我不完全確定我知道你在做什麼。我假設你想創建一個DataTable並加載你的現有對象。假設你的類看起來是這樣的:

public class MyClass { 
    public int ID {get;set;} 
    public string Column1 {get;set;} 
    public DateTime Column2 {get;set;} 
    // ... 
} 

,並假設你要複製他們的名單到一個DataTable,方法如下:

DataTable dt = new DataTable("MyTable"); 
dt.Columns.Add("ID", typeof(int)); 
dt.Columns.Add("Column1", typeof(string)); 
dt.Columns.Add("Column2", typeof(DateTime)); 

foreach (var o in _myObjectList) { 
    DataRow dr = dt.NewRow(); 
    dr["ID"] = o.ID; 
    dr["Column1"] = o.Column1; 
    dr["Column2"] = o.Column2; 
    dt.Rows.Add(dr); 
} 
1

您可以使用反射來獲取對象的字段和列添加到DataTable:

private bool IsNullableType(Type theType) 
{ 
    return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))); 
} 


// Create the columns based on the data in the album info - get by reflection 
var ai = new <your object without data>; 
Type t = ai.GetType(); 

this.dataTable.TableName = t.Name; 

foreach (PropertyInfo p in t.GetProperties()) 
{ 
    var columnSpec = new DataColumn(); 
    // If nullable get the underlying type 
    Type propertyType = p.PropertyType; 
    if (IsNullableType(propertyType)) 
    { 
     var nc = new NullableConverter(propertyType); 
     propertyType = nc.UnderlyingType; 
    } 
    columnSpec.DataType = propertyType; 
    columnSpec.ColumnName = p.Name; 
    this.dataTable.Columns.Add(columnSpec); 
} 

this.dataGridView.DataSource = dataTable; 

然後將一行添加到表:

var info = new <your object with data>; 
// Add by reflection 
Type t = info.GetType(); 
var row = new object[t.GetProperties().Length]; 

int index = 0; 
foreach (PropertyInfo p in t.GetProperties()) 
{ 
    row[index++] = p.GetValue(info, null); 
} 

this.dataTable.Rows.Add(row);