使用SqlBulkCopy导入数据,并且生成insert数据

本文介绍了一种从Excel文件中读取数据并批量导入到SQL Server数据库的方法。通过使用OleDbConnection连接Excel文件,并借助SqlBulkCopy进行高效的数据迁移。此外,还展示了如何进一步将数据插入到指定的数据库表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 protected void Button1_Click(object sender, EventArgs e)

    {

        string execelConnectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/Xmas Fusion - 10000 Coupons.xls;Extended Properties=""Excel 8.0;HDR=YES;""";

        using (OleDbConnection conn = new OleDbConnection(execelConnectionStr))

        {

            OleDbCommand cmd = new OleDbCommand("select * FROM [rental Promocodes1$]", conn);

            conn.Open();

            using (IDataReader dr = cmd.ExecuteReader())

            {

                string sqlConnectionString = @"Data Source=192.168.1.6;Initial Catalog=VP_Prod_080627;uid=VP;pwd=clochase";

                // Bulk Copy to SQL Server 

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))

                {

                    bulkCopy.DestinationTableName = "TempTest";

                    bulkCopy.WriteToServer(dr);

                }

            }

        }

        Response.Write("OK");

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        string sqlConnectionString = @"Data Source=192.168.1.6;Initial Catalog=VP_Prod_080627;uid=VP;pwd=clochase";

        FileStream file = new FileStream(@"D:/Insert.txt",FileMode.Create);

        StreamWriter w = new StreamWriter(file);

        using (SqlConnection con = new SqlConnection(sqlConnectionString))

        {

            SqlCommand cmd = new SqlCommand("select * from TempTest", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            da.Fill(dt);

            long count = 170001;

            for (int i = 0; i < dt.Rows.Count; i++)

            { 

                string insertString = string.Format("insert tblPromo values({0},'{1}','{2}')",count, dt.Rows[i]["PromoCode"].ToString(),dt.Rows[i]["PromoVersion"].ToString());

                w.WriteLine(insertString);

                count++;

            }

            w.Close();

            file.Close();

        }

        Response.Write("sheng cheng ok ");





    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值