• SQL 操作Excel (使用Jet.OLEDB,需要安装Excel)


    使用Jet.OLEDB,虽然有很多的局限性.但他无疑是与DataTable操作最方便的方法了.速度也很快.NPOI有点慢.

    1.链接:string connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX={1};'",物理地址,模式);

    模式:0:导入模式,1:导出模式:2混合模式.所对应的操作一定要选择正确的模式,要不然,可能会产生无法插入记录
    2.取所有表名:
    using (OleDbConnection objconn = new OleDbConnection(connstr))
    {
        try
        {
            objconn.Open();
            dt = objconn.GetSchema("tables");
            objconn.Close();
        }
        catch(Exception ee)
        {
            //
        }
    }
    3.取表内容
    string tbName = "";//表名后会有$
    System.Data.DataTable dt = new System.Data.DataTable();
    using (OleDbConnection objconn = new OleDbConnection(connstr))
    {
        try
        {
            objconn.Open();
            OleDbCommand cmd = objconn.CreateCommand();
            cmd.CommandText = "select * from [" + tbName + "]";
            OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
            adp.Fill(dt);
            objconn.Close();
        }
        catch(Exception ee)
        {
            //
        }
    }
    4.根据DataTable插入更新
    using (OleDbConnection objconn = new OleDbConnection(connstr))
    {

        try
        {
            objconn.Open();
            //发现手工写列名很容易出错,就提取一下表的列表
            OleDbCommand cmd = objconn.CreateCommand();
            cmd.CommandText = "select * from [Sheet1$]";
            OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
            adp.Fill(dt);

            StringBuilder hdrColumn = new StringBuilder();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                hdrColumn.Append("[" + dt.Columns[i].ColumnName.ToString() + "],");
            }
            //插入行
            foreach (DataRow dr in dataTable.Rows)
            {
                StringBuilder columnString = new StringBuilder();
                for (int i = 0; i < dataTable.Columns.Count;i++ )
                {
                    DataColumn dc = dataTable.Columns[i];
                    columnString.Append("'" + dr[dc.ColumnName] + "',");
                }
                string sqlStr = "insert into [Sheet1$] (" + hdrColumn.ToString().Trim(',') + ") values(" + columnString.ToString().Trim(',') + ")";
                OleDbCommand Cmd = new OleDbCommand(sqlStr, objconn);
                Cmd.ExecuteNonQuery();
            }

            objconn.Close();
        }
        catch(Exception ee)
        {
            //
        }
    }
    5. Jet 性质决定不支持Delete操作

     

  • 相关阅读:
    获取字符串出现的次数
    手机号码正则表达式验证
    DOM: EVENT FLOW
    AsyncCallback 异步回调委托
    高德地图
    我的json
    Arrow function restore
    constructor&object 的联系与对比
    for each/in/of的解释and example
    program发展史及以后预测
  • 原文地址:https://www.cnblogs.com/stangray/p/1804209.html
Copyright © 2020-2023  润新知