ASP.NET 将 excel 导入 SQL

button的事件,凑合着看,需要先上传到服务器然后再读取

if (FileUpload1.PostedFile != null)
        {
            string str = FileUpload1.PostedFile.FileName;
            int i = str.LastIndexOf("\\");
            String filename=str.Substring(i+1);
            FileUpload1.PostedFile.SaveAs(@Server.MapPath("xls") + filename);

            Label1.Text = "文件名为" + filename;
            string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Server.MapPath("xls") + "\\" + filename + ";Extended Properties=Excel 8.0";
            OleDbConnection thisconnection = new OleDbConnection(conn);
            thisconnection.Open();
            string Sql = "select * from [Sheet1$]";
            OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, thisconnection);
            DataSet ds = new DataSet();
            mycommand.Fill(ds, "[Sheet1$]");
            thisconnection.Close();

            string conn1 = System.Configuration.ConfigurationManager.ConnectionStrings["ZOPGConn"].ToString();
            SqlConnection thisconnection1 = new SqlConnection(conn1);
            thisconnection1.Open();
            int count = ds.Tables["[Sheet1$]"].Rows.Count;

            for (int j = 0; j < count; j++)
            {
                string id_1, id_2, id_3;
                id_1 = ds.Tables["[Sheet1$]"].Rows[j]["id1"].ToString();
                id_2 = ds.Tables["[Sheet1$]"].Rows[j]["id2"].ToString();
                id_3 = ds.Tables["[Sheet1$]"].Rows[j]["id3"].ToString();
                string excelsql = "insert into test(id1,id2,id3) values ('" + id_1 + "','" + id_2 + "','" + id_3 + "') ";
                SqlCommand mycommand1 = new SqlCommand(excelsql, thisconnection1);
                mycommand1.ExecuteNonQuery();
            }
            Response.Write("更新成功");
            thisconnection1.Close();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值