zoukankan      html  css  js  c++  java
  • C#读取excel文件的内容(使用DataSet)

    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就可以了

           

  • 相关阅读:
    《计算机网络》总结
    【操作系统】死锁
    【操作系统】进程同步
    【操作系统】处理器调度
    【操作系统】总结二(进程与线程)
    【操作系统】总结一
    前缀、中缀、后缀表达式
    QMap
    Qt 常用的功能
    Qt 文件处理
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/6004928.html
Copyright © 2011-2022 走看看