日期:2014-05-17 浏览次数:20930 次
/// <summary>
/// 读取Excel文件,内容存储在DataSet中
/// </summary>
/// <param name="opnFileName">Excel文件路径</param>
/// <returns>DataSet</returns>
public static DataSet ExcelToDataSet(string FileName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
try
{
objConn.Open();
System.Data.DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim(); //获取 Excel 的表名,默认值是sheet1
string strSql = "select * from [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
myData.Fill(ds, tableName);//填充数据
}
catch (Exception ex)
{
Console.WriteLine("错误!:" + ex.Message.ToString());
}
finally
{
objConn.Close();
objConn.Dispose();
}
&nb