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

           

  • 相关阅读:
    一个可以拖拽的div
    网页设计与制作常见问题
    如何写出兼容性很好的页面
    图片4像素底边
    响应式布局简明示例
    CSS 实现背景图尺寸不随浏览器缩放而变化
    bootstrap实现pc屏幕五等分
    css中的px、em、rem 详解
    HTML 5的革新——语义化标签(一)
    jQuery实现TAB选项卡切换特效简单演示
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/6004928.html
Copyright © 2011-2022 走看看