public static DataTable ExcelToDataTable(string strExcelFileName, string TableName = null)
{
//源的定义
String strConn = "";
FileInfo file = new FileInfo(strExcelFileName);
switch (file.Extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
//连接数据源
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable NamesTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//Sql语句
//string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
string sql = "SELECT * FROM [" + NamesTable.Rows[0][2] + "]";
if (!string.IsNullOrEmpty(TableName))
{
sql = "SELECT * FROM [" + TableName + "$" + "]";
}
OleDbDataAdapter adp = new OleDbDataAdapter(sql, strConn);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
DataTable NowDT = myDataSet.Tables[0];
return NowDT;
}
C#读取Excel至DataTable
最新推荐文章于 2024-06-12 09:48:34 发布