Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » 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.

Total page views :  56195
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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;
}


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.