using System.Data.Common;
using System.Web.UI;namespace WebExcel
{
/// <summary>
/// ExcelToTable 的摘要说明。
/// </summary>
public class ExcelToTable
{
/// <summary>
/// 返回Excel文件中的第一个数据表
/// </summary>
/// <returns></returns>
private static OleDbConnection GetExcelOledbConnection(string FileName) {
string strProvider=@"Provider=Microsoft.Jet.OLEDB.4.0;";
string strExtendProperties=@"Extended Properties=""Excel 8.0;IMEX=1;HDR=Yes""";
string strDataSource=@"Data Source="+FileName+";";
System.Text.StringBuilder sb=new System.Text.StringBuilder(strProvider);
sb.Append(strDataSource);
sb.Append(strExtendProperties);
return new OleDbConnection(sb.ToString());
}
/// <summary>
/// 通过OleDb读出的Excel表,只能读出第一张表
/// </summary>
/// <param name="FileName">可以包括路径的完整文件名</param>
/// <returns></returns>
public static DataTable GetDataTable(string FileName) {
OleDbConnection con=ExcelToTable.GetExcelOledbConnection(FileName);
con.Open();
DataTable schemaTable=con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
if(schemaTable.Rows.Count==0) {
throw new Exception("文件没有工作表");
}
            string tablename=(string)schemaTable.Rows[0]["TABLE_NAME"];
if(tablename.IndexOf("'")!=-1 )
throw new Exception("表名中不能包括',[,]");
OleDbDataAdapter dda=new OleDbDataAdapter(
"SELECT * FROM ["+tablename+"]",con);
DataTable dt=new DataTable();
dda.Fill(dt);
con.Close();
return dt;
}
}
}