如何使用dataTable?

我给出的问题是:

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

我发现了一个可以轻松导出数据表的代码片段。 所以我会把我的对象带到数据表中。 我怎样才能做到这一点?

语言是C#

我并不完全确定,我知道你在做什么。 我假设你想创build一个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); } 

您可以使用reflection来获取对象的字段并将列添加到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);