///
/// read datatable
///
///
///
///
public static System.Data.DataTable GetExcelDataTable(string path, string tname)
{
//string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='text;HDR=Yes;FMT=Delimited';Data Source=D:\\");
//OleDbConnection conn = new OleDbConnection(strConn);
//DataTable dt1 = new DataTable();
//string sql = "select * from ReportLowIDAndHighID.csv";
/*Office 2007*/
string ace = "Microsoft.ACE.OLEDB.12.0";
/*Office 97 - 2003*/
string jet = "Microsoft.Jet.OLEDB.4.0";
string xl2007 = "Excel 12.0 Xml";
string xl2003 = "Excel 8.0";
string imex = "IMEX=1";
/* csv */
string text = "text";
string fmt = "FMT=Delimited";
string hdr = "Yes";
string conn = "Provider={0};Data Source={1};Extended Properties=\"{2};HDR={3};{4}\";";
string select = string.Format("SELECT * FROM [{0}]", tname);
//string select = sql;
string ext = Path.GetExtension(path);
OleDbDataAdapter oda;
System.Data.DataTable dt = new System.Data.DataTable("data");
switch (ext.ToLower())
{
case ".xlsx":
conn = String.Format(conn, ace, Path.GetFullPath(path), xl2007, hdr, imex);
break;
case ".xls":
conn = String.Format(conn, jet, Path.GetFullPath(path), xl2003, hdr, imex);
break;
case ".csv":
conn = String.Format(conn, jet, Path.GetDirectoryName(path), text, hdr, fmt);
string filename = Path.GetFileName(path);
select = "SELECT * FROM " + filename;
//sheet = Path.GetFileName(path);
break;
default:
break;
//throw new Exception("File Not Supported!");
}
OleDbConnection con = new OleDbConnection(conn);
//打开连接
if (con.State == ConnectionState.Broken || con.State == ConnectionState.Closed)
{
con.Open();
}
System.Data.DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
//System.Data.DataTable dtSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//string[] strTableNames = new string[dtSheetName.Rows.Count];
//for (int k = 0; k < dtSheetName.Rows.Count; k++)
//{
// strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
//}
sheetName = tname.Length > 0 ? tname : sheetName;
select = "select * from [" + sheetName + "]";
//select = string.Format(select, sql);
oda = new OleDbDataAdapter(select, con);
oda.Fill(dt);
con.Close();
return dt;
}