方法一:利用OleDb直接连接Excel文件进行读取数据。
//获取Excel路径
string fileUrl = GetExcel(fuImportStudent);
//适合老旧版本的xls文件
const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"";
//适合新版的xlsx文件
//const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
System.Data.DataTable dt = null;
//建立连接
OleDbConnection connOleDb = new OleDbConnection(string.Format(cmdText, fileUrl));
//打开连接
if (connOleDb.State == ConnectionState.Broken || connOleDb.State == ConnectionState.Closed)
{
connOleDb.Open();
}
System.Data.DataTable schemaTable = connOleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取Excel的第一个Sheet名称
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
//查询sheet中的数据
string strSql = "select * from [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, connOleDb);
DataSet ds = new DataSet();
da.Fill(ds);
//将Excel数据转写成DataTable
dt = ds.Tables[0];
//关闭连接
connOleDb.Close();
if (dt.Rows.Count > 0)
{
for