Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Import MS Excel data to SQL Server table using C#

, 13 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Import MS Excel data to SQL Server table using C#.

Introduction

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

CREATE TABLE
(
STUDENT VARCHAR(64),
ROLLNO VARCHAR(16),
COURSE VARCHAR(32),
)

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:

USING SYSTEM.DATA.OLEDB;
USING SYSTEM.DATA.SQLCLIENT;

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)
{
    //declare variables - edit these based on your particular situation
    string ssqltable = "tdatamigrationtable";
    // 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 student,rollno,course 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 = "server=mydatabaseservername;user
        id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
        //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();
        //series of commands to bulk copy data from the excel file into 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
    }
}

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.

License

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

Share

About the Author

Musakkhir
Software Developer (Senior)
India India
Musakkhir Sayyed is a Software Engineer working in IT Company. He has been a programmer/Software Developer for past 2 years specializing in .NET/C# development. Currently, he is a Silverlight, WPF/Sharepoint developer specializing in BCS Services.
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionImport data from Excel to sql server table PinmemberMember 1095553717hrs 50mins ago 
BugSir I tried to integrate my code with your ode to import excel data to sql server PinmemberOmkar Hendre8-Sep-14 20:00 
QuestionNice Article PingroupSiva Hyderabad29-Jul-14 19:04 
QuestionOracle database Pinmembergowtha malar20-May-14 4:10 
AnswerImport MS Excel data to SQL Server table using C# PinmemberMember 1080649211-May-14 21:06 
QuestionYou may need to have Excel installed on a server for server-side automation (aspx) Pinmembervrsuarez11-Feb-14 15:28 
SuggestionHow to get the excel sheet name and import into sql server- continue to my previous comment [modified] Pinmemberravi24june19-Jan-14 2:36 
AnswerImport MS Excel data to SQL Server table using C# [modified] Pinmemberravi24june19-Jan-14 1:39 
Suggestionexample didn't work for me until I made a small modification. Pinmemberjohn_17265-Oct-13 8:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140905.1 | Last Updated 13 Aug 2013
Article Copyright 2013 by Musakkhir
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid