zoukankan      html  css  js  c++  java
  • 读取Excel。。。

    最近要给项目写一些小工具,来方便数据初始化,不过囧的时操作Office 2010 时遇到了小麻烦,怎么连接Excel时都是报错 “未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序”。

    系统为Server 2008 R2 ,查了各种资料,都不能完全解决问题,其实主要问题在于使用的连接字符串有问题。

    很久以前一直使用的如下:

    View Code
    1 private const string CONST_CONNECTIONSTRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcel.xls;Extended Properties=Excel 8.0;";

    现在使用2010时,需要使用如下连接字符串:

    View Code
    1 private const string CONST_CONNECTIONSTRING = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\\MyExcel.xls;Extended Properties=Excel 12.0;";

    此问题就这样的解决了。。。

    以下为读取Excel的小部分源码:

    View Code
     1         /// <summary>
     2         /// 取得Excel中的数据
     3         /// </summary>
     4         /// <param name="excelPath">excel路径</param>
     5         /// <param name="sheetName">工作表名称</param>
     6         /// <param name="queryStr">查询语句</param>
     7         /// <returns>DataTable</returns>
     8         internal DataTable GetExcelDate(string excelPath, string sheetName, string queryStr)
     9         {
    10             string connStr = string.Empty;
    11             DataTable table = new DataTable();
    12             OleDbDataReader reader = null;
    13 
    14             if (string.IsNullOrEmpty(sheetName))
    15             {
    16                 sheetName = GetFirstSheet(excelPath);
    17             }
    18 
    19             if (string.IsNullOrEmpty(excelPath))
    20             {
    21                 return null;
    22             }
    23 
    24             connStr = string.Format(CONST_CONNECTIONSTRING, excelPath);
    25 
    26             if (string.IsNullOrEmpty(queryStr))
    27             {
    28                 queryStr = string.Format("Select * from [{0}]", sheetName);
    29             }
    30 
    31             GetExcelReader(connStr, queryStr, out reader);
    32 
    33             // 填充数据表
    34             AddExcelDataTable(table, reader);
    35 
    36             // 回收使用过的资源
    37             CloseConn();
    38             CloseReader(reader);
    39 
    40             return table;
    41         }

    以上读取的方法使用的为ADO.NET,当然也可以使用OFFICE提供的API,那就看自己用哪种方法顺手了。

  • 相关阅读:
    Xcode 增强开发效率的插件
    svn 常用指令
    初识JFinal
    企业竞争案例分析
    可行性研究5
    可行性研究习题4
    可行性研究课后题
    关于阅读软件工程和计算机科学技术区别的文章来谈谈自己看法
    关于中文编程是解决中国程序员效率的秘密武器的问题思考
    Java ForkJoinPool 用法及原理
  • 原文地址:https://www.cnblogs.com/jiujiu2009/p/2334966.html
Copyright © 2011-2022 走看看