2009-07-11 47 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);