public static DataSet Read2DExce(bool hasHeader, string filePath)
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1};IMEX={2};'";
connectionString = string.Format(connectionString, filePath, hasHeader ? "YES" : "NO", 1);
OleDbConnection connection = new OleDbConnection(connectionString);
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());
adapter.Fill(excelData);
excelData.Tables[i].TableName = dr["TABLE_NAME"].ToString().Replace("$", "");
}
return excelData;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
可以实现多个sheet的读入,但是如何显示读入的效果,还需要我们各位大侠去继续研究,希望有识之士回复答案,期待............. |