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

           

  • 相关阅读:
    关于求 p_i != i and p_i != i+1 的方案数的思考过程
    poj 3041 Asteroids 二分图最小覆盖点
    poj 1325 Machine Schedule 最小顶点覆盖
    poj 1011 Sticks 减枝搜索
    poj 1469 COURSES 最大匹配
    zoj 1516 Uncle Tom's Inherited Land 最大独立边集合(最大匹配)
    Path Cover (路径覆盖)
    hdu 3530 SubSequence TwoPoint单调队列维护最值
    zoj 1654 Place the Rebots 最大独立集转换成二分图最大独立边(最大匹配)
    poj 1466 Girls and Boys 二分图最大独立子集
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/6004928.html
Copyright © 2011-2022 走看看