如果你经常光临Insus.NET的博客,你会留意到有一篇博文 Asp.net读取Excel文件 那只是列出Excel两个版本的连接语句。但是你的专案在应用时,也许不能固定用户只上传某一种版本的Excel文件而你在专案中取舍使用哪一种连接字串,所以你会尝试使用下面方法去解决,判断上传的Excel文件是什么版本的:
View Code
public
static
string
GetExcelConnectionString(
string
file)
{
string connectionString = string .Empty;
string fileExtension = file.Substring(file.LastIndexOf( " . " ) + 1 );
switch (fileExtension)
{
case " xls " :
connectionString = " Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + HttpContext.Current.Server.MapPath(file) + " ;Extended Properties='Excel 8.0;HDR=YES;IMEX=1' " ;
break ;
case " xlsx " :
connectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + HttpContext.Current.Server.MapPath(file) + " ;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1' " ;
break ;
}
return connectionString;
}
{
string connectionString = string .Empty;
string fileExtension = file.Substring(file.LastIndexOf( " . " ) + 1 );
switch (fileExtension)
{
case " xls " :
connectionString = " Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + HttpContext.Current.Server.MapPath(file) + " ;Extended Properties='Excel 8.0;HDR=YES;IMEX=1' " ;
break ;
case " xlsx " :
connectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + HttpContext.Current.Server.MapPath(file) + " ;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1' " ;
break ;
}
return connectionString;
}
在专案中调用时(代码部分):
View Code
//
从数据库取得上传的Excel文件名
string file = objDictionary[ " FileFullName " ].ToString();
// 获取中Excel的连接字串。
string excelConnectionString = GetExcelConnectionString(file);
// 传入至OleDbConnection实例中去
OleDbConnection objConn = new OleDbConnection(excelConnectionString);
string sql = " SELECT * FROM [Sheet1$] " ;
OleDbDataAdapter ObjDa = new OleDbDataAdapter(sql, objConn);
DataSet objDs = new DataSet();
ObjDa.Fill(objDs);
string file = objDictionary[ " FileFullName " ].ToString();
// 获取中Excel的连接字串。
string excelConnectionString = GetExcelConnectionString(file);
// 传入至OleDbConnection实例中去
OleDbConnection objConn = new OleDbConnection(excelConnectionString);
string sql = " SELECT * FROM [Sheet1$] " ;
OleDbDataAdapter ObjDa = new OleDbDataAdapter(sql, objConn);
DataSet objDs = new DataSet();
ObjDa.Fill(objDs);