internal static DataTable GetExcelSheet(string excelFile,string sheetName = "")
{
string fullPathToExcel = Path.GetFullPath(excelFile);
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel " + (excelFile.ToLower().EndsWith("x") ? "12.0" : "8.0") + ";HDR=yes'", fullPathToExcel);
return GetDataTable(connString, "SELECT * FROM [" + (string.IsNullOrEmpty(sheetName) ? GetTableName(connString, 0) : sheetName + "$") + "]");
}
private static DataTable GetDataTable(string connectionString, string sql)
{
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
private static string GetTableName(string connectionString, int row = 0)
{
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
conn.Open();
return conn.GetSchema("Tables").Rows[row]["TABLE_NAME"] + "";
}
catch { }
finally { conn.Close();}
return "sheet1";
}