sql server - importing excel to sql c# -


i have been trying import excel table sql database. have tried example:

     void importdata(string excelfilepath)      {         //declare variables - edit these based on particular situation         string ssqltable = "ttableexcel";         // make sure sheet name correct, here sheet name sheet1,      can change sheet name if have         string myexceldataquery = "select student,rollno,course [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 = "server=mydatabaseservername;userid=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";              string sclearsql = "delete " + ssqltable;            sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);            sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);            sqlconn.open();            sqlcmd.executenonquery();            sqlconn.close();            //series of commands bulk copy data excel file our sql table             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;            while (dr.read())            {               bulkcopy.writetoserver(dr);            }             oledbconn.close();         }         catch (exception ex)         {            //handle exception         }      } 

my programming not , cannot make work. there nothing wrong sql connection (the db cleared after running program). not able information database. excel file called test.xlsx , stored in d:\users\haners. database tabe called test. how can make program import information in excel file database???

previous code :

       sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);        bulkcopy.destinationtablename = ssqltable;        while (dr.read())        {           bulkcopy.writetoserver(dr);        } 

new code :

       sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);        bulkcopy.destinationtablename = ssqltable;        bulkcopy.batchsize=100;        bulkcopy.writetoserver(dr); 

hope resolve issue. happy coding. cheers


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -