读取Excel文件到DataSet

  /// <summary>
  /// 读取Excel文件
  /// </summary>
  /// <param name="exPath">本地文件绝对路径</param>
  /// <returns></returns>
  public DataSet ReadExcelData(string strExcelPath)
  { 
   OleDbConnection oledbConn = null;
   OleDbDataAdapter comm =null;   
   try
   {
    //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + strExcelPath;
    string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';data source=" + strExcelPath;
    oledbConn = new OleDbConnection(strCon);
    oledbConn.Open();
    DataSet ds = new DataSet();
    DataTable dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null, null, null, "TABLE"});
    foreach(DataRow dr in dt.Rows)
    {
     string tableName = dr["TABLE_NAME"].ToString();
     string strSql = "SELECT * FROM [" + tableName + "]";
     string name = tableName.Remove(tableName.Length-1,1);
     if (name.ToLower()=="merit_project_data")
     {
      comm = new OleDbDataAdapter(strSql,oledbConn);
      comm.Fill(ds, name.ToLower() );
      comm.Dispose();
     }
    }
    oledbConn.Close();
    return ds;
   }
   catch(Exception ex)
   {
    throw ex;
   }
   finally
   {
    comm.Dispose();
    oledbConn.Dispose();
   }
  }
  
posted @ 2012-02-22 16:46  顿金  阅读(212)  评论(0编辑  收藏  举报