Click here to Skip to main content
Licence CPOL
First Posted 9 Dec 2008
Views 17,375
Downloads 956
Bookmarked 40 times

Simple Excel 2007 Data Loader to SQL 2008 Server

By | 9 Dec 2008 | Article
Simple Excel data loader to SQL Server using SQlBulkCopy
 
Part of The SQL Zone sponsored by
See Also

Introduction

This is a very simple Excel 2007 data loader to SQL 2008 database. I am using SqlBulkCopy class to make data load fast. (10K record loaded in less than 3s).

One catch: You will need existing table in SQL DB with matching columns. I skipped dynamic table creation to keep the code simple.

Using the Code

This is the most basic version, without error checking to make the code clear. Below is the completed code behind the form.

Button 1 - Opens the Excel file.

Button 2 - Uploads data to SQL Server.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;

namespace SimpleExcelLoader
{
    public partial class Form1 : Form
    {
        string filename="";
        public Form1()
        {
            InitializeComponent();
        }
      private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "Excel 2007 files 
			(*.xlsx)|*.xlsx|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
               filename = openFileDialog1.FileName;
               textBox1.Text = filename;
               button2.Enabled = true;
               toolStripStatusLabel1.Text = "File Selected. 
				Enter DB Info and click Upload Data";
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string server = textBox2.Text;
            string db = textBox3.Text;
            string user = textBox4.Text;
            string pass = textBox5.Text;
            string tableName=textBox6.Text;
            string serverConnectionString="Server="+server+";
			Database="+db+";Uid="+user+";Pwd="+pass+";";
            
            
            //step 1
            // Load Excel data into DataTable
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
            Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=YES;'";
            string strSQL = "SELECT * FROM [Sheet1$]";
            OleDbConnection excelConnection = new OleDbConnection(connectionString);
            excelConnection.Open(); // This code will open excel file.
            OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);
            // create data table
            DataTable dTable = new DataTable();
            //fill table with Excel data
            dataAdapter.Fill(dTable);
           
            //step 2 
            //connect to server
            
            using (SqlConnection destinationConnection =
                   new SqlConnection(serverConnectionString))
                {                   
                    destinationConnection.Open();   
             
                    using (SqlBulkCopy bulkCopy =
                            new SqlBulkCopy(destinationConnection))
                    {
                        //Destination Table must match columns in Excel sheet
                        bulkCopy.DestinationTableName = tableName;
                                              
                        try
                        {
                            // Write from the source to the destination.
                            bulkCopy.WriteToServer(dTable);
                            toolStripStatusLabel1.Text="Data Uploaded";
                        }                                                  
                        catch (Exception ex)
                        {                           
                            toolStripStatusLabel1.Text=ex.Message;
                        }
                       
                     destinationConnection.Close(); }}
    
                // dispose used objects
                dTable.Dispose();
                dataAdapter.Dispose();
                dbCommand.Dispose();
                excelConnection.Close();
                excelConnection.Dispose();
            }}}

Points of Interest

The code was tested with Excel 2007 and SQL Server 2008.

History

  • 9th December, 2008: Initial post

License

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

About the Author

Mia Wallace

Software Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalxlsx 2 sql PinmemberBernie Su7:05 16 Jun '09  
GeneralSSIS... PinmemberTarabanko Yury14:26 9 Dec '08  
GeneralRe: SSIS... PinmemberInga Bemman23:53 9 Dec '08  
GeneralRe: SSIS... PinmemberTarabanko Yury3:54 10 Dec '08  
GeneralWell... PinmemberJayDial14:07 9 Dec '08  
GeneralRe: Well... PinmemberInga Bemman23:49 9 Dec '08  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 9 Dec 2008
Article Copyright 2008 by Mia Wallace
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid