/// <summary>
/// 將Excel表格數據轉換成Datatable
/// </summary>
/// <param name="fileUrl">文件地址</param>
/// <param name="table">table命名</param>
/// <returns></returns>sql
public DataTable GetExcelDatatable(string fileUrl, string table)
{
//office2007以前 僅支持.xls
//const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
//支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes表明第一行是標題,不是數據;
string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";ide
System.Data.DataTable dt = null;
//創建鏈接
OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
try
{
//打開鏈接
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
}ui
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sqlstr = string.Empty;
foreach (DataRow item in schemaTable.Rows)
{
//獲取Excel的第一個Sheet名稱
string sheetName = item["TABLE_NAME"].ToString().Trim();
//查詢sheet中的數據
string strSql = "select * from [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
DataSet ds = new DataSet();
try
{
da.Fill(ds, table);
}
catch (Exception)
{orm
throw;
}cmd
dt = ds.Tables[0];
}
return dt;
}
catch (Exception exc)
{
throw exc;
}
finally
{
conn.Close();
conn.Dispose();
}
}string