首页 > 解决方案 > 通过 Oledb c# 防止重复数据从 Excel 到 db

问题描述

我有一个 excel,我想用一个按钮将其中的四列上传到 SQL 表。问题是当我重复单击按钮时,所有数据都将被复制,但我不希望这样。我只想更新新数据。我的查询:

protected void Button1_Click(object sender, EventArgs e)
    {
        int UserID;
        int InsuID;
        string Result;
        int Year;

        //** مسیر فایل اکسل**
        String ExcelPath = @"D:\Insu_lab.xlsx";

        //** کانکشن به آفیس**
        OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
        mycon.Open();
        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
        OleDbDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {

            UserID = Convert.ToInt32(dr[0].ToString());
            InsuID = Convert.ToInt32(dr[1].ToString());
            Result = dr[2].ToString();
            Year = Convert.ToInt32(dr[3].ToString());

            savedata(UserID, InsuID, Result, Year);
            Label1.Text = "اطلاعات با موفقیت در  دیتابیس ذخیره شد";

        }
    }

    private void savedata(int UserID, int InsuID, string Result, int Year)
    {
        String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
        String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
        SqlConnection con = new SqlConnection(mycon);
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = query;
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
    }

标签: c#asp.netsql-serverexcel

解决方案


解决方案 1:当您clicked打开时button,that( button) 禁用该按钮。

Button1.disable = true;

导出结束时:

Button1.disable = false;

解决方案2:您可以在这部分使用from jquery ajax。


推荐阅读