public DataSet TransExcelToDataSet(string fileName, List<string> sheetNames)
{
OleDbConnection objConn =null;
DataSet data =new DataSet();
//创建读取excel连接
string strConn ="Provider=Microsoft.Jet.OleDb.4.0;"+"data source="+ fileName
+";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
try
{
objConn =new OleDbConnection(strConn);
using (objConn)
{
OleDbDataAdapter sqlada =null;
//遍历从配置文件中读取的sheet名称
foreach (string sheetName in sheetNames)
{
if (!string.IsNullOrEmpty(sheetName))
{
string strSql ="select \* From \["+ sheetName.Trim() +"$\]";
sqlada =new OleDbDataAdapter(strSql, objConn);
//填充dataset
sqlada.Fill(data, sheetName);
}
}
}
}
catch (Exception e)
{
thrownew Exception("将excel中指定sheet内容读入dataset出错!"+ e.Message +" strConn: "+ strConn +" ; fileName:"+ fileName);
//throw e;
}
finally
{
if (objConn !=null)
{
objConn.Dispose();
objConn.Close();
}
GC.Collect();
}
return data;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章