真心急啊
解决方案 »
- 关于 插入数据库总是多插一条的问题
- 两个事件的回车键顺序的问题
- C#新手玩软件...问开发工具...
- ASP 程序里的 session 如何传给 ASP.NET
- 跪求高手求解!!!!!!!!
- C#winform中Picturebox使用
- 扩展性DTE对象不可用
- C#winfrom excel导出报错:System.InvalidCastException: 接口 Microsoft.Office.Interop.Exc
- Windows应用程序中,如何进行datagrid绑定?
- 有没有办法在MDI主窗体中,打开数据库的连接后在子窗体就不用再连接?
- 简单正则再求
- C#中 一开始点击“上一行”就溢出,求解?!
using(OleDbConnection Conn= new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath +";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";"))
{
var strCom = " SELECT * FROM " + sheetName;
Conn.Open();
var myCommand = new OleDbDataAdapter(strCom,Conn);
var ds = new DataSet();
myCommand.Fill(ds);
Conn.Close();
}
/// 读取复杂的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file"></param>
/// <returns></returns>
public static List<T> ReadExcel<T>(string file)
{
List<T> list = new List<T>();
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;IMEX=1'";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connString))
{
using (System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", conn))
{
conn.Open();
DataSet ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
DataTable dt = ds.Tables[0]; Type type = typeof(T);
PropertyInfo[] infos = type.GetProperties();
Dictionary<string, string> dicProperties = new Dictionary<string, string>();
foreach (PropertyInfo info in infos)
{
object[] attributes = info.GetCustomAttributes(typeof(PropertyAttribute), true);
if (attributes != null && attributes.Length > 0)
{
PropertyAttribute pa = (PropertyAttribute)attributes[0];
dicProperties.Add(pa.Name, info.Name);
}
} foreach (DataRow row in dt.Rows)
{
T obj = (T)Activator.CreateInstance(typeof(T));
try
{
Fill<T>(row, dt.Columns, obj, dicProperties);
}
catch (Exception)
{
break;
}
list.Add(obj);
}
}
}
return list;
}
这个够你消化的了