添加命名空间:using System.Data.OleDb; ////// 从excel表格加载数据返回DataSet /// /// excel路径 /// 查询excel的sql命令,为“”或null默认查询Sheet1表 ///返回DataSet public static DataSet LoadFromExcel(string path,string sql_Command) { string strConn; /* HDR=NO: 第一行也作为数据行 IMEX=1: 把所有列都做为字符串来读取 */ strConn = @"Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + path + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件/此連接可以操作.xls與.xlsx文件 OleDbConnection oleConn = new OleDbConnection(strConn); DataSet ds = new DataSet(); if (sql_Command == null || sql_Command == "") { try { oleConn.Open(); string sql = "select * from [Sheet1$]"; OleDbDataAdapter adapter = new OleDbDataAdapter(sql, oleConn); adapter.Fill(ds); return ds; } catch { throw new Exception("加载失败!"); } finally { oleConn.Close(); } } else { oleConn.Open(); OleDbDataAdapter adapter = new OleDbDataAdapter(sql_Command, oleConn); adapter.Fill(ds); return ds; } }