public static DataSet ObjectArrayToDataSet(object[] objArr)
{
if (objArr.Length == 0)
return null;
DataSet ds = CreateDataSet(objArr[0].GetType());
ds = FillDataSet(ds, objArr);
string path="E:\\学习文档\\dataset.txt";
string title="";
EduceToTxTFromSql(ds, path, title);
return ds;
}
public static DataSet CreateDataSet(Type t)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
PropertyInfo[] pis = t.GetProperties();
foreach (PropertyInfo pi in pis)
{
DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
dt.Columns.Add(dc);
}
return ds;
}
public static DataSet FillDataSet(DataSet ds, object[] objArr)
{
DataColumnCollection dcs = ds.Tables[0].Columns;
Type t = objArr[0].GetType();
foreach (object obj in objArr)
{
DataRow dr = ds.Tables[0].NewRow();
for (int i = 0; i < dcs.Count; i++)
{
dr[i] = t.InvokeMember(dcs[i].ColumnName, BindingFlags.GetProperty, null, obj, null);
}
ds.Tables[0].Rows.Add(dr);
}
return ds;
}
//导出文本
public static void EduceToTxTFromSql(DataSet ds, string path, string title)
{
System.Data.DataTable dt = ds.Tables[0];
//创建要导出信息的流【先创建一个流(根据具体情况创建什么流),再创建流的处理对象(读或者写)】
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
//写入标题
sw.Write(title);
sw.WriteLine();
//写入信息
string s = " | ";
foreach (DataRow dr in dt.Rows)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = "str" + j;
str = dr[j].ToString();
sw.Write(str);
sw.Write(s);
}
sw.WriteLine();
}
sw.Flush();
sw.Close();
}