码迷,mamicode.com
首页 > Windows程序 > 详细

C#读取excel文件的内容(使用DataSet)

时间:2016-10-27 19:38:05      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:pat   路径   out   for   target   select   string   处理   分享   

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

异常处理:

 1.如果出现 External table is not in the expected format.

      技术分享

      大部分都是因为路径中的OLEDB或者Extended Properties与当前的Excel文件版本不对应导致的,本人当时就是如下情况:

      旧的:string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;";

  修改后:string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";

  2.如果出现 The ‘XXXXXXXXX‘ provider is not registered on the local machine

      技术分享

      那是因为Platform target配置不当的问题,OLEDB貌似只支持x86, 所以你只需要到项目属性 -> Bulid -> Platform target -> x86就可以了

       技术分享

 

C#读取excel文件的内容(使用DataSet)

标签:pat   路径   out   for   target   select   string   处理   分享   

原文地址:http://www.cnblogs.com/tommy-huang/p/6004928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!