Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The below is my code to import data from excel to database.But when i enter new data in excel and uploading it to database all the data is again inserting into database.My requirement is only newly inserted file in excel should be upload to database

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Excel;
using System.Text;
using System.Reflection;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class apload : System.Web.UI.Page
{
    // int count = 0;
    string sName = "";
    DataSet ds = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter();
    cnt1 cn = new cnt1();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        int n = cn.upd();
        if (FileUpload1.HasFile)
        {
            sName = FileUpload1.FileName;
            Console.Write(sName);

            string ext = System.IO.Path.GetExtension(sName);

            if (ext == ".xls")
            {
                FileUpload1.SaveAs(Server.MapPath("../App_Data/" + "Books" + ext));

            }

        }
        sName = FileUpload1.FileName.ToString();
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\" + sName + "; Extended Properties=\"Excel 8.0;HDR=YES\"");
        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn);
        //cmd.Connection = conn;
        //OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
        //DataSet ds = new DataSet();
        //adapter.Fill(ds, "ex");
        //count = ds.Tables["ex"].Rows.Count;
        //gdvEx.DataSource = ds;
        //gdvEx.DataBind();
        //int count = ds.Tables["ex"].Rows.Count;
        //for (int i = 0; i <= count; i++)
        //{


        //}
        try
        {
            //After connecting to the Excel sheet here we are selecting the data using select statement from the Excel sheet
            OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", conn);

            conn.Open();
            ocmd.Connection = conn;
            OleDbDataAdapter adapter = new OleDbDataAdapter(ocmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds, "ex");
            int cnt = ds.Tables["ex"].Rows.Count;
            gdvEx.DataSource = ds;
            gdvEx.DataBind();
            //deletedatafromsql();
            //Here [Sheet1$] is the name of the sheet in the Excel file where the data is present
            OleDbDataReader odr = ocmd.ExecuteReader();
            string EmployeeID;
            string FirstName = "";
            string LastName = "";
            string Address = "";
            string Gender = "";

            while (odr.Read())
            {
                EmployeeID = valid(odr, 0);//Here we are calling the valid method
                FirstName = valid(odr, 1);
                LastName = valid(odr, 2);
                Address = valid(odr, 3);
                Gender = valid(odr, 4);

                //Here using this method we are inserting the data into the database
                if ((int)cnt != n)
                {
                    insertdataintosql(EmployeeID, FirstName, LastName, Address, Gender);
                }

           }
            conn.Close();
        }

        catch (DataException ee)
        {
            lblmsg.Text = ee.Message;
            lblmsg.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            lblmsg.Text = "Data Inserted Sucessfully";
            lblmsg.ForeColor = System.Drawing.Color.Green;
        }
    }

    private string valid(OleDbDataReader myreader, int stval)//if any columns are 
    //found null then they are replaced by zero
    {
        object val = myreader[stval];
        if (val != DBNull.Value)
            return val.ToString();
        else
            return Convert.ToString(0);
    }

    public void insertdataintosql(string EmployeeID, string FirstName, string LastName, string Address, string Gender)
    {
        //inserting data into the Sql Server
        SqlConnection con = new SqlConnection("Server=SREEKANTH-MSFT\\SQLEXPRESS;Database=Example;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        // cmd.CommandText = "select * from Employee";

        cmd.CommandText = "insert into Employee(EmployeeID,FirstName,LastName,Address,Gender)values(@EmployeeID,@FirstName,@LastName,@Address,@Gender)";
        cmd.Parameters.Add("@EmployeeID", SqlDbType.NVarChar).Value = EmployeeID;
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = FirstName;
        cmd.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = LastName;
        cmd.Parameters.Add("@Address", SqlDbType.NVarChar).Value = Address;
        cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = Gender;
        cmd.CommandType = CommandType.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    
}
Posted
Updated 27-Jul-11 4:39am
v2

It's obvious that you have no code to difference the old file and the new one. The easiest solution is to delete the old data, in fact, that's the only way to do an update that includes if data was removed, or at least, the best.
 
Share this answer
 
I think you need to update if the record exists using the
SQL
EmployeeID
, if not insert it. You'll need to process the complete file. And create a log to identify which action or error was taken for each record.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900