C#读取Excel文件的内容,通过OLEDB来连接,关键是连接的路径,
如:string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
     连接的路径涉及3方面:

     1. Provider:使用的是OLEDB连接,但是这个技术会不时更新,使用前查询最新的版本;

     2. Data Source: 就是Excel文件的路径;

     3. Extended Properties: 指定Excel的版本,同上,使用前查询最新的版本(要与读取的Excel文件保存一致);

读取不同的Sheet,方式跟SQL类似:
  string strExcel = "select * from [sheet3$]";

 1 public DataSet ReadFile(string filePath)
 2         {
 3             string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;"; 
 4             OleDbConnection conn = new OleDbConnection(strConn);
 5             conn.Open();
 6             string strExcel = "select * from [sheet3$]";
 7             OleDbDataAdapter da = new OleDbDataAdapter(strExcel, strConn);
 8             DataSet ds = new DataSet();
 9             try
10             {
11                 da.Fill(ds);
12             }
13             catch (Exception ex)
14             {
15                 throw new Exception("读取Excel失败:" + ex.Message);
16             }
17             return ds;
18         }
View Code

相关文章: