If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow the below steps:
Step 1: Let’s take an example to import data to SQL Server table. I am going to import student information data from an MS Excel sheet to the tStudent SQL table:
Step 2: Now design a tStudent table in SQL Server
Your MS Excel sheet and SQL table are ready, now it’s time to write C# code to import the Excel sheet into the tStudent table.
Step 3: Add these two namespaces in your class file:
Step 4: Add below method in your class file, you can call this method from any other class and pass the Excel file path:
public void importdatafromexcel(string excelfilepath)
string ssqltable = "tdatamigrationtable";
string myexceldataquery = "select student,rollno,course from [sheet1$]";
string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = "server=mydatabaseservername;user
string sclearsql = "delete from " + ssqltable;
sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);
sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);
oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring);
oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn);
oledbdatareader dr = oledbcmd.executereader();
sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);
bulkcopy.destinationtablename = ssqltable;
catch (exception ex)
In the above function you have to pass the MS Excel file path as a parameter. If you want to import your data by providing the client access to
select the Excel file and import, then you might have to use the ASP.NET File control and upload the Excel file on the server in some temp folder, then use
the file path of the uploaded Excel file and pass the path in the above function. Once data import is complete then you can delete the temporary file.
The above method first deletes the existing data from the destination table, then imports the Excel data into the same table.
Musakkhir Sayyed is a Software Engineer working in IT Company. He has been a programmer/Software Developer for past 5 years specializing in .NET/C# development.