ADO.NET 连接access 和 excel

来源:互联网 发布:tester软件 编辑:程序博客网 时间:2024/05/16 14:19

 

连接Access : Data Source 也可以写.mdb的路径 ,不过不是太安全。

Code:
  1. string str = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("access.mdb") + "";   
  2.   
  3.             OleDbConnection conn = new OleDbConnection(str);   
  4.   
  5.             try  
  6.             {   
  7.                 conn.Open();   
  8.                 Response.Write("success!");   
  9.             }   
  10.             catch (Exception)   
  11.             {   
  12.                 Response.Write("Exception!");   
  13.                 throw;   
  14.             }  

连接 Excel : 连接Excel必须注意它的格式 。否则连接会失败。

Code:
  1. string str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("test.xls") + ";Extended Properties= Excel 8.0;";   
  2.             OleDbConnection conn = new OleDbConnection(str);   
  3.             try  
  4.             {   
  5.                 conn.Open();   
  6.                 Response.Write("打开成功!");   
  7.                 OleDbDataAdapter oda = new OleDbDataAdapter("select * from [Sheet1$]",conn);   
  8.   
  9.                 DataSet ds = new DataSet();   
  10.                 int count = oda.Fill(ds,"excleData");   
  11.                 for (int i = 0; i < count ; i++)   
  12.                 {   
  13.                     Response.Write(ds.Tables["excleData"].Rows[i]["姓名"].ToString()+"<br/><hr/>");   
  14.                 }   
  15.             }   
  16.             catch (Exception)   
  17.             {   
  18.                 Response.Write("出现异常!");   
  19.                 throw;   
  20.              }  

  结果 如图:

 

 加我为好友 希望和大家共同学习。