anand m

anand m

  • 1.4k
  • 337
  • 34.6k

Unable to load first record in excel(.xls)

Jan 12 2023 4:42 PM

Hello All,

I am trying to load excel (.xls) data import to SQL DB table, but i am not able to insert first  record data into SQL table.

I am using C#.net and backend SQL server 2016.

My code :

public void ImportDataFromExcel(string excelFilePath)
{
    //declare variables - edit these based on your particular situation
    string ssqltable = "SP_GES_Usersrequest";
    DataTable dtSQlbulk = new DataTable();
    // make sure your sheet name is correct, here sheet name is sheet1,
    // so you can change your sheet name if have    different
    string myexceldataquery = "select* from [Sheet1$]";
    try
    {
        //create our connection strings
        string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath +
        ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
        string ssqlconnectionstring = "Data Source=";
        //execute a query to erase any previous data from our destination table
        string sclearsql = "delete from " + ssqltable;
        SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
        SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
       
        sqlconn.Open();
        sqlcmd.ExecuteNonQuery();
     
        sqlconn.Close();
        OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
        OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
        oledbconn.Open();
        OleDbDataReader dr = oledbcmd.ExecuteReader();
       
        SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
        bulkcopy.DestinationTableName = ssqltable;


Answers (4)