經常會用到,廢話不多說直接貼代碼
//讀取Excel文件
public static DataTable ReadExcelToTable(string path)//excel存放的路徑
{
try
{
//連接字符串
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
//讀取sheetName
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string firstSheetName = sheetsName.Rows[0][2].ToString();
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
DataSet set = new DataSet();
ada.Fill(set);
return set.Tables[0];
}
}
catch (Exception)
{
return null;
}
}
//把讀取到的數據轉換為 list
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定義集合
IList<T> ts = new List<T>();
// 獲得此模型的類型
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 獲得此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo p in propertys)
{
tempName = p.Name; // 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
p.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}