zoukankan      html  css  js  c++  java
  • 将Excel表格数据转换成Datatable

    /// <summary>
    /// 将Excel表格数据转换成Datatable
    /// </summary>
    /// <param name="fileUrl">文件地址</param>
    /// <param name="table">table命名</param>
    /// <returns></returns>

    public DataTable GetExcelDatatable(string fileUrl, string table)
    {
    //office2007之前 仅支持.xls
    //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
    //支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是标题,不是数据;
    string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

    System.Data.DataTable dt = null;
    //建立连接
    OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
    try
    {
    //打开连接
    if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
    {
    conn.Open();
    }


    System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    string sqlstr = string.Empty;
    foreach (DataRow item in schemaTable.Rows)
    {
    //获取Excel的第一个Sheet名称
    string sheetName = item["TABLE_NAME"].ToString().Trim();
    //查询sheet中的数据
    string strSql = "select * from [" + sheetName + "]";
    OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
    DataSet ds = new DataSet();
    try
    {
    da.Fill(ds, table);
    }
    catch (Exception)
    {

    throw;
    }

    dt = ds.Tables[0];
    }
    return dt;
    }
    catch (Exception exc)
    {
    throw exc;
    }
    finally
    {
    conn.Close();
    conn.Dispose();
    }
    }

  • 相关阅读:
    FTP-实例(Md5验证)
    Socket-实例
    函数对象、函数嵌套、名称空间与作用域、装饰器
    Docker——手动创建镜像
    Docker——桥接网络配置
    Docker——网络和存储(数据卷)
    Docker-PS命令解析
    面试题44:扑克牌的顺子
    面试题42:翻转单词顺序VS左旋转字符串
    面试题41:和为s的两个数字VS和为s的连续正数序列
  • 原文地址:https://www.cnblogs.com/AbelAngelo/p/10909800.html
Copyright © 2011-2022 走看看