如何使用dataTable?

时间:2009-07-11 11:42:46

标签: c# excel datatable

我给出的问题如下:

我有一个x列的对象,每列都有y值。我现在必须将它带入Excel。

我找到了一个可以轻松导出数据表的代码段。所以我将把我的对象带到数据表中。我怎么能这样做?

语言是C#

2 个答案:

答案 0 :(得分: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 :(得分: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);