datatable,list<T>,html转换

开篇要扯淡

chedan

将List转换成DataTable

 1         public static DataTable ToDataTable<T>(this IList<T> data)
 2         {
 3             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
 4             DataTable dt = new DataTable();
 5             for (int i = 0; i < properties.Count; i++)
 6             {
 7                 PropertyDescriptor property = properties[i];
 8                 dt.Columns.Add(property.Name, property.PropertyType);
 9             }
10             object[] values = new object[properties.Count];
11             foreach (T item in data)
12             {
13                 for (int i = 0; i < values.Length; i++)
14                 {
15                     values[i] = properties[i].GetValue(item);
16                 }
17                 dt.Rows.Add(values);
18             }
19             return dt;
20         }

Excel转table

 1  public static DataTable InputFromExcel(string ExcelFilePath, string TableName)
 2         {
 3             if (!File.Exists(ExcelFilePath))
 4             {
 5                 throw new Exception("Excel文件不存在!");
 6             }
 7  
 8             //如果数据表名不存在,则数据表名为Excel文件的第一个数据表
 9             ArrayList TableList = new ArrayList();
10             TableList = GetExcelTables(ExcelFilePath);
11  
12             if (TableName.IndexOf(TableName) < 0)
13             {
14                 TableName = TableList[0].ToString().Trim();
15             }
16  
17             DataTable table = new DataTable();
18             OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0");
19             OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);
20             OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
21  
22             try
23             {
24                 if (dbcon.State == ConnectionState.Closed)
25                 {
26                     dbcon.Open();
27                 }
28                 adapter.Fill(table);
29             }
30             catch (Exception exp)
31             {
32                 throw exp;
33             }
34             finally
35             {
36                 if (dbcon.State == ConnectionState.Open)
37                 {
38                     dbcon.Close();
39                 }
40             }
41             return table;
42         }

 

posted @ 2015-06-19 15:22  若云  阅读(189)  评论(0)    收藏  举报