zoukankan      html  css  js  c++  java
  • 用C#读取Excel返回DataSet

    不添加任何 excel dll 引用,代码很简单,就不做解释了。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.Common;
    
    namespace OCXMLCreater.ExcelProvider
    {
        public class ExcelHelper
        {
            //唯一需要解释的一点是这个连接字符串中,HDR=YES 表示此Excel表第一行用于显示字段名称(Header),如果没有字段名,则应 HDR=NO
            public static string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\WorkSpace\MyDocument\Samples2.xlsx;Extended Properties=""Excel 8.0;HDR=YES;""";
    
            /// <summary>
            /// 读取 Excel 返回 DataSet
            /// </summary>
            /// <param name="connectionString">Excel 连接字符串</param>
            /// <param name="commandString">查询语句, for example:"SELECT ID,userName,userAddress FROM [Sheet1$]" </param>
            /// <returns></returns>
            public static DataSet GetExcelDataSet(string connectionString, string commandString)
            {
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
    
                DbDataAdapter adapter = factory.CreateDataAdapter();
    
                DbCommand selectCommand = factory.CreateCommand();
                selectCommand.CommandText = commandString;  //commandString例如:"SELECT ID,userName,userAddress FROM [Sheet1$]"
    
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;
    
                selectCommand.Connection = connection;
                adapter.SelectCommand = selectCommand;
    
                DataSet cities = new DataSet();
                adapter.Fill(cities);
    
                connection.Close();
                return cities;
            }
        }
    }
    
    
  • 相关阅读:
    定义字符串数组
    ifconfig 修改IP
    空指针与野指针的区别
    GDB和Core Dump使用笔记
    雅虎(ycsb)测试hbase(压测)
    decode函数的几种用法
    NVL函数:空值转换函数
    hive行转列,列转行
    case when then else end用法
    hive中一般取top n时,row_number(),rank,dense_ran()常用三个函数
  • 原文地址:https://www.cnblogs.com/leco/p/1881330.html
Copyright © 2011-2022 走看看