/// <summary>
/// 获取 Excel 连接对象。
/// </summary>
/// <param name="strFullPath">文件的完全路径</param>
/// <param name="isTreatedHeader">第一列是否设置为列名</param>
/// <param name="intIMEXMode">输入输出模式。1:设置输入为文本 Text 类型,通常使用该值。0/2:设置输入为 多数 Majority 类型,此设置极易导致数据缺失发生。</param>
/// <returns>Excel 连接对象</returns>
public static OleDbConnection GetExcelConnection( string excelPath, bool includeHeader, int IMEXMode )
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1};IMEX={2};'";
connectionString = string.Format( connectionString, excelPath, includeHeader ? "YES" : "NO", IMEXMode );
return new OleDbConnection( connectionString );
}
/// <summary>
/// 从Excel中读取数据
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="includeHeader">是否包含列信息,(第一行作为列)</param>
/// <returns>excel包含的数据集</returns>
public static DataSet ReadExcel2DataSet(string filePath,bool includeHeader)
{
OleDbConnection connection = GetExcelConnection( filePath , includeHeader , 1 );
try
{
connection.Open();
DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[] {null, null, null, "TABLE"});
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand();
adapter.SelectCommand.Connection = connection;
DataSet excelData = new DataSet();
for( int i=0; i< schemaTable.Rows.Count; i++)
{
DataRow dr = schemaTable.Rows[i];
adapter.SelectCommand.CommandText = string.Format("SELECT * FROM {0}", dr["TABLE_NAME"].ToString().Trim('/''));
adapter.Fill(excelData);
excelData.Tables[i].TableName = dr["TABLE_NAME"].ToString();
}
return excelData;
}
catch
{
throw;
}
finally
{
if(connection != null)
{
connection.Close();
}
}
}
【备注】:
HDR=Yes 是说Excel文件的第一行是列名而不是数据;HDR=No 正好与前面的相反。
IMEX=1 输入输出模式。1:设置输入为文本 Text 类型,通常使用该值。0/2:设置输入为 多数 Majority 类型,此设置极易导致数据缺失发生。
如果连接时报错:"外部表不是预期的格式" 请参照下面的连接字符串进行修正:
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + Server.MapPath("ExcelFiles/MyExcelFile.xls") + ";Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'"; //此连接只能操作Excel2003(.xls)文件
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Server.MapPath("ExcelFiles/Mydata2007.xlsx") + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串)
所以请根据自身的Excel版本选择对应的连接字符串。