Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » COM Interop » Import data from Excel to Access using ADO.net

Import data from Excel to Access using ADO.net

Data interoperability with Microsoft office applications has become easier with ADO.net.

Page Views : 76774
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Data interoperability with Microsoft office applications has become easier with ADO.net.

The Microsoft Office System exposes objects through COM objects. Microsoft released a suite of Primary Interop Assemblies (PIAs) that are optimized for accessing COM objects from .NET-based assemblies. These generally get installed into your system when you install MS office.

The data can be easily transferred from an Excel spreadsheet to an access database using ADO.net and suite of these Microsoft office interop assemblies. Here first we will make use of Microsoft Jet OLE DB provider to establish connection to an excel spreadsheet. The process to be followed is as under:

Create an Excel sheet you want to transfer data from. Let's assume the file is named Book.xls and the first sheet is the default sheet Sheet1.

Add reference to Microsoft Office Access Interop Assembly.

 

Right click on added reference's property to ensure that the Path of the assembly points to GAC.

e.g.:

C:\WINDOWS\assembly\GAC\Microsoft.Office.Interop.Access\10.0.4504.0__31bf3856ad364e35\Microsoft.Office.Interop.Access.dll

Remove any previously created Access file and create a new one to import data into.

if (File.Exists(@"C:\Book.mdb"))

{

    File.Delete(@"C:\ Book.mdb");

}

Access.Application _accessData;

_accessData = new Access.ApplicationClass();

_accessData.Visible = false;

_accessData.NewCurrentDatabase(@"C:\ Book.mdb");

_accessData.CloseCurrentDatabase();

_accessData.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll);
_accessData = null;

Now let's establish connection to our data source (Excel file) using Microsoft Jet OLE DB provider.

 

string _filename = @"C:\Book.xls";

string _conn;

_conn = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + _fileName + ";" +

"Extended Properties=Excel 8.0;";
OleDbConnection _connection = new OleDbConnection(_conn);

Use OledbCommand object to select all the data from sheet1 and execute a ExecuteNonQuery to import data into Book.mdb.

OleDbCommand _command = new OleDbCommand();

_command.Connection = _connection;

try

{

    _command.CommandText = @"SELECT * INTO [MS Access;Database=C:\Book.mdb].[Sheet1] FROM [Sheet1$]";

    _connection.Open();

    _command.ExecuteNonQuery();

    _connection.Close();

    MessageBox.Show("The import is complete!");

}

catch (Exception)

{

    MessageBox.Show("Import Failed, correct Column name in the sheet!");
}

This will create a new mdb data file called Book.mdb on your disc containing Sheet1 data. You will notice that table Sheet1 in Book.mdb file has taken the first rows of Sheet1 as the column names. That means that first row of your sheet contains header row data. The attribute "HDR=yes;" in connection string specifies this.

The full Code is here:

//call this method by supplying it the Data Source file //name, which in the example is Book.xls

public static void CheckUpdateDBFile(string filename)

{

    if (File.Exists(@"C:\Book.mdb"))

    {

        File.Delete(@"C:\Book.mdb");

    }

    Access.Application _accessData;

    _accessData = new Access.ApplicationClass();

    _accessData.Visible = false;

    _accessData.NewCurrentDatabase(@"C:\Book.mdb");

    _accessData.CloseCurrentDatabase();

    _accessData.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll);

    _accessData = null; 

    OleDbConnection _connection = MakeExcelConnection(filename);

    FillAccessDatabase(_connection);           

}

private static OleDbConnection MakeExcelConnection(string fileName)

{                       

    string _conn;

    _conn = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + fileName + ";" + 

    "Extended Properties=Excel 8.0;";

    OleDbConnection _connection = new OleDbConnection(_conn);

    return _connection;
}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Vandita Pandey
Vandita is a software engineer with having 5+ yrs of experience in development. She holds a degree in Bachelors of Engineering. She is also an E-commerce certified. She is currently working as a senior software engineer with a CMMi 5 level company .
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Primary Key by c code On March 14, 2007
Hi Vandita, This is a Great piece of code. I was just wondering how to set the Primary key of C:\Book.mdb using c# code? Thanks
Reply | Email | Modify 
Re: Primary Key by Vandita On March 20, 2007

Hi,

You may need to establish connection to this Access Db using OLEDB Data provider, then use ADO.net to assign primary key to the table by assigning a DataColumn to it.

Thanks for the post.

Vandita

Reply | Email | Modify 
Need ur kind help by sam On March 22, 2007
Hello Vandita..namashkar.. I need ur kind help. I manage to compile the programme but i found the following error. "Import Failed, correct Column name in the sheet!" In my excel file, i just have one column data like following: column1 A B C But i failed to import the data into Access. Please help. Thanks.
Reply | Email | Modify 
Re: Need ur kind help by Vandita On March 22, 2007

Hi,

that means the exception is being raised, the message you are stating is the one in the catch block. Please debug the process and find out the exact exception message. That might help you in resolving the issue.

Cheers!!

Reply | Email | Modify 
Re: Re: Need ur kind help by sam On March 22, 2007

Hello vandita, thanks for the prompt reply.

The error Message is " Could not find installable ISAM"..

What does it mean?

Thanks..

Regards,

-sam-

Reply | Email | Modify 
Could not installable ISAM by SUHASINI On March 23, 2007
hi this is suhasini... To resolve your problem..You have to give the User Id as Admin in your connection statement
Reply | Email | Modify 
Errors, cant get sample to work by stan On April 2, 2007
Hello Vandita, I keep getting the same error on VS2003 and VS2005. Error: Error 1 The type or namespace name 'office' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\StanM\My Documents\Visual Studio 2005\Projects\ExcelToAccess\ExcelToAccess\Form1.cs 14 7 ExcelToAccess. I do have the using office directive and the assembly reference. My Microsoft Object ref. is 11.0 instead of 10.0. Could you please post all your directives or a complete working sample? Thanks,
Reply | Email | Modify 
Errors, cant get sample to work by stan On April 2, 2007
Hello Vandita, I keep getting the same error on VS2003 and VS2005. Error: Error 1 The type or namespace name 'office' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\StanM\My Documents\Visual Studio 2005\Projects\ExcelToAccess\ExcelToAccess\Form1.cs 14 7 ExcelToAccess. I do have the using office directive and the assembly reference. My Microsoft Object ref. is 11.0 instead of 10.0. Could you please post all your directives or a complete working sample? Thanks,
Reply | Email | Modify 
Errors, cant get sample to work by stan On April 2, 2007
Hello Vandita, I keep getting the same error on VS2003 and VS2005. Error: Error 1 The type or namespace name 'office' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\StanM\My Documents\Visual Studio 2005\Projects\ExcelToAccess\ExcelToAccess\Form1.cs 14 7 ExcelToAccess. I do have the using office directive and the assembly reference. My Microsoft Object ref. is 11.0 instead of 10.0. Could you please post all your directives or a complete working sample? Thanks,
Reply | Email | Modify 
how do you set HDR=yes in select statement? by stan On April 2, 2007
Hello Vandita, I figured out previous errors and sorry for the multiple posts (I was not signed in...). Now the program exits at the exeption "import Failed..." What is the complete sql statement to set HDR=yes? Thanks,
Reply | Email | Modify 
how do you set HDR=yes in select statement? by stan On April 2, 2007
Hello Vandita, I figured out previous errors and sorry for the multiple posts (I was not signed in...). Now the program exits at the exeption "import Failed..." What is the complete sql statement to set HDR=yes? Thanks,
Reply | Email | Modify 
sql command fails by stan On April 2, 2007
Hello Vandita, I can open the connection now and set the HDR=YES properly, but my code fails on the command sql query. Is there a way you could break it up into two pices so that i can see which one is problematic? One sql which writes to the Access db and the other which gets gata from Excel and binds it to a variable or data gris or something. Thanks,
Reply | Email | Modify 
sql command fails by stan On April 2, 2007
Hello Vandita, I can open the connection now and set the HDR=YES properly, but my code fails on the command sql query. Is there a way you could break it up into two pices so that i can see which one is problematic? One sql which writes to the Access db and the other which gets gata from Excel and binds it to a variable or data gris or something. Thanks,
Reply | Email | Modify 
sql command fails by stan On April 2, 2007
Hello Vandita, I can open the connection now and set the HDR=YES properly, but my code fails on the command sql query. Is there a way you could break it up into two pices so that i can see which one is problematic? One sql which writes to the Access db and the other which gets gata from Excel and binds it to a variable or data gris or something. Thanks,
Reply | Email | Modify 
sql command fails by stan On April 2, 2007
Hello Vandita, I can open the connection now and set the HDR=YES properly, but my code fails on the command sql query. Is there a way you could break it up into two pices so that i can see which one is problematic? One sql which writes to the Access db and the other which gets gata from Excel and binds it to a variable or data gris or something. Thanks,
Reply | Email | Modify 
sql command fails by stan On April 2, 2007
Hello Vandita, I can open the connection now and set the HDR=YES properly, but my code fails on the command sql query. Is there a way you could break it up into two pices so that i can see which one is problematic? One sql which writes to the Access db and the other which gets gata from Excel and binds it to a variable or data gris or something. Thanks,
Reply | Email | Modify 
How to give Database Password by tset On April 18, 2007
Hi Vandita This is hemal. I need your help. I can create the database with the code...But how to give password to database. Thanks.
Reply | Email | Modify 
Want code in C# by Ishwar On October 3, 2007
Hi Vandita, This is a Great piece of code. I was just converted this code in C# application I got error at statement : accessData.Quit(Microsoft.Office.Core..Interop.Access.AcQuitOption.acQuitSaveAll); error is : C:\Ishwar\Test\Main.cs(399): The type or namespace name 'Interop' does not exist in the class or namespace 'Microsoft.Office' (are you missing an assembly reference?) plz give suggesstion for above error.. Waiting for ur reply.. Thank you.
Reply | Email | Modify 
Want code in C# by Ishwar On October 3, 2007
Hi Vandita, This is a Great piece of code. I was just converted this code in C# application I got error at statement : accessData.Quit(Microsoft.Office.Core..Interop.Access.AcQuitOption.acQuitSaveAll); error is : C:\Test\Main.cs(399): The type or namespace name 'Interop' does not exist in the class or namespace 'Microsoft.Office' (are you missing an assembly reference?) plz give suggesstion for above error.. Waiting for ur reply.. Thank you.
Reply | Email | Modify 
As a beginner by Kervin On October 29, 2007
Good Day, i am a beginner who is trying to learn C# and ASP.net on my own, can you recommend some sites/readings i look at?
Reply | Email | Modify 
when access database has password then which attribute to write? by Rahul On November 22, 2007
hi mem when access database has password then which attribute to write?
Reply | Email | Modify 
Saket Dwivedi by saket On February 9, 2008
hi mem this is saket dwivedi we want help from you can you give me i m working as software engineer dwivedi_saket@rediffmail.com saket
Reply | Email | Modify 
Code in VB.NET by Santanu On March 16, 2008
Hello Madam. This is a Great piece of code. Its working, but I want this code with Condition cheeking, suppose In Access data Base Table 1: Product(PCode,Desc) Example: P001,Furniture P002,Books..... Table 2: SubProduct(ProductCode,SubProductCode,Desc) Example: P001,SP001,Chair P001,SP002,Table P002,SP003,Magazine.... Tabel 3: Transaction(ProductCode,SubProductCode,TotalSales) In The Exel Sheet A(Product) B(SProduct) C(Sales) 1 Furniture Chair 20 2 Furniture Table 30 3 Books Magazine 12 . . Now I want to retrieve data first from A1, then take the code from the Product Table and store in a variable then I retrieve data from B1, then take the code from the SubProduct Table and store in a variable ans Last I retrieve data from C1 and store in a variable. The Transaction table look like this. P001,SP001,20 P001,SP002,30 P002,SP003,12 Plz help me..... Regards Santanu
Reply | Email | Modify 
Error compiling code by Brian On March 25, 2008
Hello Vandita, What namespace is the FillAccessDatabase() function in. I can compile your example code except for this line. This is the error message I'm getting: The name FillAccessDatabase does not exist in the class or namespace Thanks, Brian
Reply | Email | Modify 
Access to Excel Automation by johira On February 13, 2009
Hi Vandita I have some problem in transfering data from access to excel.my question is here:http://www.mrexcel.com/forum/showthread.php?p=1838871&posted=1#post1838871 I wonder if you could help me.thnx
Reply | Email | Modify 
hi by rama On October 27, 2009
i got error in your code
what is Fillaccessdatabase
variable or method
its show fillaceessdatabase is unknow error
Reply | Email | Modify 
Error plz help by Varsha On May 18, 2010

when i execute this statement (colored in red below) it gives error  External table is not in the expected format.


try

{

    _command.CommandText = @"SELECT * INTO [MS Access;Database=C:\Book.mdb].[Sheet1] FROM [Sheet1$]";

    _connection.Open();

    _command.ExecuteNonQuery();

    _connection.Close();

    MessageBox.Show("The import is complete!");

}

catch (Exception)

{

    MessageBox.Show("Import Failed, correct Column name in the sheet!");
}


please Help

Reply | Email | Modify 
Same Method but inserting? by Corey On June 22, 2010
Ok, I got this all to work and created the database just fine. Now I want to use this same method again to insert all data from the excel sheet (there is only one worksheet in my file) into the database.

I will get weekly new spreadsheets with the same column names and I want to be able to update the database with the new data.

I have been playing around with it for a few days now, but the best I get is an error in the insert statement. For the record, this is the last insert statement I used:

_command.CommandText = @"INSERT ALL INTO [MS Access;Database=Pearson.mdb].[washington] SELECT * FROM [" + sheet + "$]";


Reply | Email | Modify 
The type or namespace name 'Access' could not be found (are you missing a using direftive or an assembly reference?) by sy On July 19, 2010
I had make the reference to add Microsoft Access 11.0 Object Library, but during compile, i getting error "The type or namespace name 'Access' could not be found (are you missing a using directive or an assembly reference?)"
pls help...
Reply | Email | Modify 
FYI by felix On November 3, 2010

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace Console_Excel2007_Access
{
    class Program
    {
        static void Main(string[] args)
        {

            string strDeleteAccess = "";
            string strGetDataFromExcel = "";
            string strInsertIntoAccess = "";
            OleDbConnection oleDbConnAccess;
            OleDbConnection oleDbConnExcel;
            OleDbCommand oleDbCmdAccess;
            OleDbCommand oleDbCmdExcel;
            OleDbDataReader oleDbDataReaderExcel;

            try
            {

                //oleDbConnAccess = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Directory.GetCurrentDirectory() + "\\ff.mdb");
                //oleDbConnAccess = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\test.mdb");
                oleDbConnAccess = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.IO.Directory.GetCurrentDirectory() + "\\ff.accdb");
               
                oleDbConnAccess.Open();
                strDeleteAccess = "delete from ff_sales_082 ";
                oleDbCmdAccess = new OleDbCommand(strDeleteAccess, oleDbConnAccess);
                oleDbCmdAccess.ExecuteNonQuery();
                oleDbCmdAccess.Dispose();
                oleDbConnAccess.Close();


                oleDbConnExcel = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=;Extended properties=Excel 12.0;Data Source=" + System.IO.Directory.GetCurrentDirectory() + "\\FF_Sales_082zhengda(1).xlsx");
                // oleDbConnExcel = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=E:\\FF_Sales_082zhengda(1).xls");
                oleDbConnExcel.Open();
                strGetDataFromExcel = "SELECT * FROM [Sheet1$A11:G]";   //????????
                oleDbCmdExcel = new OleDbCommand(strGetDataFromExcel, oleDbConnExcel);
                oleDbDataReaderExcel = oleDbCmdExcel.ExecuteReader();
                if (oleDbDataReaderExcel.HasRows == true)
                {
                    oleDbConnAccess.Open();
                    for (; ; )
                    {
                        if (oleDbDataReaderExcel.Read() == true)
                        {
                            strInsertIntoAccess = "insert into ff_sales_082([RCPT_NO],[RCPT_DATE],[TIME],[EXT_P$T$],[EXT_D$T$],[TENDER],[RCPT_TYPE]) values('" + oleDbDataReaderExcel.GetValue(0).ToString() + "','" + oleDbDataReaderExcel.GetValue(1).ToString() + "','" + oleDbDataReaderExcel.GetValue(2).ToString() + "','" + oleDbDataReaderExcel.GetValue(3).ToString() + "','" + oleDbDataReaderExcel.GetValue(4).ToString() + "','" + oleDbDataReaderExcel.GetValue(5).ToString() + "','" + oleDbDataReaderExcel.GetValue(6).ToString() + "') ";
                            oleDbCmdAccess = new OleDbCommand(strInsertIntoAccess, oleDbConnAccess);
                            oleDbCmdAccess.ExecuteNonQuery();
                            oleDbCmdAccess.Dispose();
                        }
                        else
                            break;
                    }
                    oleDbConnAccess.Close();
                }
                oleDbDataReaderExcel.Close();
                oleDbCmdExcel.Dispose();
                oleDbConnExcel.Close();

            }

            catch (Exception ex)
            {
                throw ex;
            }


        }
    }
}

Reply | Email | Modify 
error message "the table already exist" by sheoherd On January 28, 2011
hi i am having problems,i want to import an excel file into a table which is in ms the message ,"table already exists "is displayed , but when i change the table name ,the code is executed very well, with nothing being inserted in the database.the code is as follows: Dim _filename As String = "C:\Users\administrator\Documents\import.xls" _conn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & _filename & ";" & "Extended Properties=""Excel 8.0;HDR=YES;IMEX=1"";" Dim _connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(_conn) 'Use OledbCommand object to select all the data from sheet1 and execute an ExecuteNonQuery to import data into Book.mdb. Dim _command As OleDb.OleDbCommand = New OleDb.OleDbCommand() _command.Connection = _connection ' Try ' _command.CommandText = "SELECT * INTO [MS Access;Database=C:\Book.mdb].[Sheet1] FROM [Sheet1$]" _command.CommandText = "SELECT * INTO [MS Access;Database=staff.mdb].[sheet1] FROM [Sheet1$]" _connection.Open() _command.ExecuteNonQuery() _connection.Close() 'MessageBox.Show("The import is complete!") 'Catch e1 As Exception MessageBox.Show("Import Failed, correct Column name in the sheet!") ' 'End Try
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.