【问题标题】:Upload and update excel file上传和更新excel文件
【发布时间】:2018-09-21 10:55:00
【问题描述】:

我有一个任务是上传 excel 文件,如果找到相同的记录,还要检查更新,我已经将 excel 文件上传到数据库中,它工作正常。

现在,我必须检查是否插入了相同的记录然后更新,否则插入新记录,我首先有两个表,我在临时表中插入记录,然后我用原始表检查临时表,如果记录匹配,则更新其他插入,我使用嵌套 for 循环来检查记录 我的循环工作正常并插入前两条记录,但是当涉及到第三条记录时,然后多次插入它并在第四条再次插入多次,请指导我做错了什么 到目前为止,这是我的代码

       protected void btnUpload_Click(object sender, EventArgs e)
{
    try
    {
        int id;
        string contactPerson;
        string designation;
        string company;
        string contact;
        string emailaddress;
        string city;
        string region;
        string industry;
        string division;
        string mobile;
        string address;

        string path = Path.GetFileName(FileUpload1.FileName);
        path = path.Replace(" ", "");

        FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
        String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
        OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");

        mycon.Open();

       DeleteRecords();

        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
        OleDbDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            if (dr[0].ToString() != "")
            {
                // Response.Write("<br/>"+dr[0].ToString());
                id = Convert.ToInt32(dr[0].ToString());
                contactPerson = dr[1].ToString();
                designation = dr[2].ToString();
                company = dr[3].ToString();
                emailaddress = dr[4].ToString();
                contact = dr[5].ToString();
                mobile = dr[6].ToString();
                address = dr[7].ToString();
                city = dr[8].ToString();
                region = dr[9].ToString();
                industry = dr[10].ToString();
                division = dr[11].ToString();

                InsertTemp(id, contactPerson, designation, company, emailaddress, contact,
                 mobile, address, city, region, industry, division);

                //InsertOrignal(id, contactPerson, designation, company, emailaddress, contact,
                // mobile, address, city, region, industry, division);

            }

            else
            {
                break;
            }


            String myconn = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
            SqlConnection conn = new SqlConnection(myconn);
            conn.Open();
            DataTable dt_temp = new DataTable();
            DataTable dt_orignal = new DataTable();
            SqlDataAdapter da_temp = new SqlDataAdapter("select * from Tbl_ExcelData order by id asc", conn);
            SqlDataAdapter da_orignal = new SqlDataAdapter("select * from Tbl_ExcelUploadData order by id asc", conn);

            da_temp.Fill(dt_temp);
            da_orignal.Fill(dt_orignal);


            if (dt_orignal.Rows.Count > 0)
            {

                for (int i = 0; i < dt_temp.Rows.Count; i++)
                {
                    for (int j = 0; j < dt_orignal.Rows.Count; j++)
                    {
                        if (dt_temp.Rows[i]["email"].ToString() == dt_orignal.Rows[j]["email"].ToString())
                        {
                            //Update Record if required
                        }
                        else
                        {
                            //insert record into orignal table


                            InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);


                        }
                    }

                }
            }

            else
            {
                InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);

            }

        }

       lblmessage.Text = "Data Has Been Updated Successfully";

        mycon.Close();
        File.Delete(ExcelPath);

    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.Message);
    }



}



private void InsertTemp(int id, String contactPerson, String designation, String company, String emailaddress, 
                             String contact, String mobile, String address,String city,String region,String industry,
                             String division)
{


    //String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
    SqlConnection con = new SqlConnection(mycon);
    con.Open();




            string query = "insert into Tbl_ExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = query;
            cmd.Connection = con;
            cmd.ExecuteNonQuery();

        }


private void InsertOrignal(int id, String contactPerson, String designation, String company, String emailaddress,
                            String contact, String mobile, String address, String city, String region, String industry,
                            String division)
{


    //String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
    SqlConnection con = new SqlConnection(mycon);
    con.Open();




    string query = "insert into Tbl_ExcelUploadData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();

}


private void DeleteRecords()
{

    SqlConnection con = new SqlConnection(mycon);
    con.Open();
    string query = "Delete from Tbl_ExcelData";
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();

}


 }

【问题讨论】:

  • 一旦您将数据从 excel 上传到临时表,那么使用简单的 SQL 过程调用而不是逐条记录来处理两个表之间的协调(更新或插入)可能更容易/更好来自应用程序。
  • 我支持@RajeshBhat,但要回答您的问题:问题:您一直在阅读和比较来自da_temp 的所有记录,以查找插入到InsertTemp 中的每一行。解决方案:您需要先读取excel并插入所有记录,然后才能开始比较过程。提示:你的 while 循环应该在第一个 else 语句之后结束。

标签: asp.net sql-server sql-server-2008


【解决方案1】:

如果您有临时表只是为了检查原始表中是否存在该行,那么这不是一个好习惯。

使用主键id或任意Unique Key直接检查原始表中是否存在该行,然后决定是Insert还是Update

一种方法,

while (dr.Read()) 
{
    if (dr[0].ToString() != "") 
    {
       id = Convert.ToInt32(dr[0].ToString());        //add other columns which needs to be fetched from Excel
       string query = "select count(1) from Tbl_ExcelData where id=?";        //To check if the row already exsits    
       SqlCommand cmd = new SqlCommand(con);

       cmd.CommandText = query;
       cmd.Paramaters.Add(new SqlParameter(1, id));

       int count = (Int32) cmd.ExecuteScalar();

       if (count > 0) //which means row already exists
       {
          //Your update code goes here
       } 
       else 
       {
            InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
       }
}

在cmets之后,这里有一个基本的想法。一种可以将 Excel 数据加载到 DataTable 并循环遍历它并决定 Upsert 的方法。记得了解MultipleActiveResultSets

try
{
    string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
    string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
    string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
    string _excelQuery = "select * from [Sheet1$]";
    DataTable tempDataTable = null;

    using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
    {
        conn.Open();
        using (var cmd = new OleDbCommand(_excelQuery, conn))
        {
            using (var reader = cmd.ExecuteReader())
            {
               var dt = new DataTable();

               dt.Load(reader); //this will load your excel data into DataTable

               tempDataTable = dt;
            }
        }
    }

    using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
    {
        sqlConn.Open();

        string countQuery = "select count(1) from Tbl_ExcelData where id=:id";    

        using(var cmd = new SqlCommand(countQuery, sqlConn))
        {
            var param = new SqlParameter("@id");

            foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
            {
                var id = row["id"]; //get the id column from the excel
                var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel

                cmd.Paramaters["@id"] =  id;

                int count = (int) cmd.ExecuteScalar();

                if (count) //row already exist in original table
                {
                    //update the row in original table
                }
                else
                {
                    //insert the row in original table
                    InsertOriginal(sqlConn, id, contactPerson);
                }
            }               
        }
     }
 }
 catch(Exception ex)
 {
 }

function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
    string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('@id','@contactPerson');

    using(var cmd = new SqlCommand(insertQuery, conn))
     {
         cmd.Parameters.Add(new SqlParameter("@id",id));
         cmd.Parameters.Add(new SqlParameter("@contactPerson", contactPerson));
         cmd.ExecuteNonQuery();
     }
}

另外,这不是经过测试的代码。欢迎随时发表评论。

【讨论】:

  • 我没有将记录直接插入到原始表中,首先将其插入到临时表中,然后将临时表与原始表进行匹配。这是一个好方法吗?并且基于电子邮件 ID,我正在匹配记录,因为电子邮件 ID 在数据中是唯一的
  • 不,插入临时表只是为了与原始表进行比较不是一个好方法。只需在插入原始表之前直接检查条件。检查更新的代码
  • 也指导我上传更新excel文件的好方法
  • @mbhthiaranidharan88,代码工作正常,只是想知道插入查询是一次插入一条记录还是一次全部插入
  • 最后一件事要问,在插入记录时,它说“contactPerson”列不属于表,你能指导我插入吗,因为我的表中有名为contactPerson的列,如我之前分享过代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多