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

How to Read Microsoft Excel 2007 Using a Connection String in C#

By , 28 Nov 2007
 
Screenshot - readExcel1.gif

Introduction

This article explains how to connect to Microsoft Excel 2007 using ADO.NET Connection string and populate a DataGridView on a form.

Using the Code

First create a C# Windows application using Visual Studio. Add the following controls to the main form from the tool box.

  • DataViewGrid control (name as dgvExcelList)
  • BindingSource control (name as dataBindingSrc)
  • Button control (name as btnPopulate)

Now open Microsoft Excel 2007 and enter a few records. Save the file and close Excel.

I have already created a sample Excel 2007 file which is available in the project folder of the demo project. If you want, you can use it by copying to C:\. The name of the Excel file is Members.xlsx.

Copy the following codes into the btnPopulate_Click event and run the application. you will find the dgvExcelList is filled with all the entries in Sheet1 of the Excel file.

Note: If you want to use your own Excel file or save the Members.xlsx file in a different location other than C:\, change the file and path name from the connection string.

Code

// You can change C:\Members.xlsx to any valid path 
// where the file is located.

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
    FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
				Data Source=C:\Members.xlsx;Extended
    FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
				Properties=""Excel 12.0;HDR=YES;"""; 
// if you don't want to show the header row (first row) in the grid
// use 'HDR=NO' in the string

string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open(); // this will open an Excel file
OleDbCommand dbCommand = new OleDbCommand(strSQL,excelConnection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);

// create data table
DataTable dTable = new DataTable();

dataAdapter.Fill(dTable);

// bind the datasource
dataBingingSrc.DataSource = dTable;
// assign the dataBindingSrc to the DataGridView
dgvExcelList.DataSource = dataBingingSrc;

// dispose used objects
dTable.Dispose()
dataAdapter.Dispose();
dbCommand.Dispose();
excelConnection.Close();
excelConnection.Dispose();

Your suggestions and comments are most welcome.

History

  • 28th November, 2007: 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

Mihadh
Software Developer (Senior) Dhivehisoft
Maldives Maldives
Member
No Biography provided

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.
Search this forum  
    Spacing  Noise  Layout  Per page   
Question...memberaditya_prestige22 Dec '12 - 8:56 
Is there a necessary driver or connector that you need to install ??
 
because whenever i run my code it says...
 
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
 
M i missing a driver or sumthing ??
 
thanx ..
BugGetting Error :membermansooralikhan5 May '12 - 21:39 
Hai,
 
first of all, thax for sharing ur artical,its very usefull to all.
When i run this code am getting error : " The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine "
 
Even i installed MS-Office 2007 AccessDatabaseEngine.exe in my system. its getting error.
Please guide me.
 
Thanks
MAK
GeneralRe: Getting Error :membertaith14 Nov '12 - 5:02 
Hello,
 
I changed CPU-type from Any CPU to x86.
 
best regards,
Gerbert
QuestionHow to Import Excel data to Ms access DatabasememberPrabakaranM8 Mar '12 - 2:34 
Hai sir,
 
I have finish my import coding, but one error should be continue, how to solve that error...pls help me sir,
 
Error:
 
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
Questioneeception arised after this....membertripti_kumbhat18 Feb '12 - 6:24 
it is giving error.
 
could not find installed ISAM.
GeneralMy vote of 5memberAlisettar30 Dec '11 - 22:01 
Thank you very much. It was so useful
QuestionThank YoumemberfreshonlineMax21 Oct '11 - 20:28 
Very Well
QuestionDo i need Access installed on my system for this?memberMember 453129822 Sep '10 - 0:03 
Iam getting error "Microsoft.ace.Oledb.4.0" is not installed on you system.
 
Please hlp me I am very frustated Mad | :mad:
QuestionRetieve the data from excel 2007 when the worksheet is open [modified]memberjaanu_simi16 Aug '10 - 23:57 
Hi...
 
i m working on a project where i m retrieving data from excel 2007 using ACE OLE DB. No problem in the code its working fine but only when the worksheet is close. when i m trying the same by keeping the worksheet open i m getting error.
 
If any one know the solution please share with me.
Thanks in advance....

modified on Tuesday, August 17, 2010 6:05 AM

GeneralMy vote of 5memberdidi212013 Aug '10 - 6:31 
De gran ayuda !!!
GeneralAlien CodememberWisam E. Mohammed25 Jun '10 - 6:49 
I think there are some alien code in the code sample.
QuestionHow to support different versions of Excelmembermetazone27 Jan '09 - 15:02 
I wrote a windows form application in C# that uses ADO.Net to read from an Excel file. I receive xls files but have to manually save them as xlsx files because I can't get the program to read xls files (I get "External table is not in the expected format"). As an aside, for broadest .net compatibility, I set each of the Projects (which create assemblies/dlls) for the application to .net framework 2.0.
 
I have 2 questions:
1. How can I get my program to read xls files when Excel 2007 is installed?
2. How can I support environments where Excel 2002 and Excel 2003 are installed - I assume different connection strings and have the users ONLY open xls files?
 
Code Snippet:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = "whatever";
connection.Open();

Connection strings I've tried:
 
// The first one worked for xlsx files w/ Excel 2007 installed:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=myFile.xls;Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;""
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=myFile.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1;""
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=myFile.xls;Extended Properties=""Excel 5.0;HDR=Yes;IMEX=1;""
AnswerRe: How to support different versions of ExcelmemberCikaPero17 Jul '11 - 22:23 
If you have typed DataSet you can easily import Excel to DataSet from different Excel formats (XLS, XLSX, CSV, ODS) with this Excel C# / VB.NET library.
This component doesn't use Excel Interop so you don't need to worry which version of Excel app is installed.
 
Here is a sample Excel C# code how to do it:
var excelFile = new ExcelFile();
 
excelFile.LoadXls(excelFileName);
 
foreach (DataTable dataTable in dataSet.Tables)
{
    var worksheet = excelFile.Worksheets[dataTable.TableName];
    worksheet.ExtractToDataTable(dataTable, worksheet.Rows.Count, ExtractDataOptions.None, worksheet.Rows[0], worksheet.Columns[0]);
}

GeneralFound a bug in vista and VS 2008membernewbieprogrammerguy24 Sep '08 - 16:05 
If u purely download and try to run the project it will give you a debugging error saying that there is no such file exists ( a runtime error) so what i basically did was change this line of default code to this
THIS
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Members.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
 
To
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\FYP\examplefollow\examplefollow\Members.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
 
as u can see that i have specified the whole file path i wonder if this is a bug that the program cnnot directly find it in a directory
For newbies like me take note that examplefollow is my solution name and the whole path is only to my computer and not to yours so change it to the path on your computer
 
and dun forget to thank to MIDAH for giving this wonderful tutorial
GeneralRe: Found a bug in vista and VS 2008memberashish diwakar22 Sep '09 - 19:00 
In C# the connectionString would be like
 
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\FYP\examplefollow\examplefollow\Members.xlsx;Extended Properties=\"Excel 12.0;HDR=YES;\"";
GeneralExcel 2007 - Reading more than 256 columns from a sheet using OLEDBmemberFad12320 May '08 - 3:51 
I am using Excel 2007 and currently using OLEDB driver to read excel sheet. The problem I am having is - the resultant record set only reads data untill 255 columns. Although Excel 2007 allows far greater column limit, I am unable to utilize this facility. Any suggestion regarding this will be highly appreciated!
 
Following is the connection string I am using for OLEDB
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ FilePath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
 
And then use the olddb dataadabter:
da = new OleDbDataAdapter("SELECT * FROM [MyWork1$]", con);
da.Fill(ds);
 
Thanks in advance,
Fad
GeneralRe: Excel 2007 - Reading more than 256 columns from a sheet using OLEDBmembernishit.amin@successcraft.com16 Jun '09 - 4:04 
Hi Did you get solution to this query....?
GeneralRe: Excel 2007 - Reading more than 256 columns from a sheet using OLEDBmemberokay2gonow22 Jun '09 - 9:57 
This will work.
SELECT * from [MyNamedRange]
 
or
 
SELECT * from [Sheet1$A1:B10]
GeneralRe: Excel 2007 - Reading more than 256 columns from a sheet using OLEDBmemberstranger_From_Tepa6 Nov '09 - 12:24 
Can you elaborate more on this?
 
I am new reading Excel files and I dont quite understand the From part on you query.
GeneralRe: Excel 2007 - Reading more than 256 columns from a sheet using OLEDBmemberstranger_From_Tepa10 Nov '09 - 13:10 
Greetings,
 
I also have an issue with the 255 columns limitations on Excel 2007 files. My file contains over 2700 columns. When I query the file using "Microsoft.ACE.OLEDB.12.0" I only get 255 columns. I searched the Web and nothing comes up.
 
Any ideas?
QuestionCan I read Opened Excel file continuosly?memberMember 458580414 Jan '08 - 9:59 
Hi,
 
I tried reading excel file using Timer_Tick for every 5 seconds (used OLEDB and VB.NET 2005) so that I can update the data in DataGridView with the latest data from Excel. It is continuous process that I need to look at the excel and update the changes in Form. But my program having problem with memory keep going up and after long time, it crashes by throwing some exception.
 
Can u tell me is there anyway to do this task without memory related issue? Excel file should be open and it has data of 300 rows and 10 columns.
 
Thanks very much for your time. Expecting for some guidance.
 
Ramesh
 
Code is below:
-----------------------------------------------
 
Imports System.Data
Imports System.Data.OleDb
 
Public Class Form1
 
Public theOleDbCommand As OleDbCommand
Public theOleDbDataAdapter As OleDbDataAdapter
Public theDataSet As DataSet
 
Public SelectString As String = "SELECT * FROM `SimpleRange` " + _
"WHERE (AlarmStatus = 1)"
 
Public ConnectionString As String = " Provider=Microsoft.Jet.OLEDB.4.0; " & _
" Data Source=C:\testminimum.xls; " & _
" Extended Properties=Excel 8.0;"
 

Public Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
 
Timer1.Interval = 5000
Timer1.Enabled = True
 
Me.theOleDbCommand = New OleDbCommand(Me.SelectString, New OleDbConnection(Me.ConnectionString))
Me.theOleDbDataAdapter = New OleDbDataAdapter(Me.theOleDbCommand)
Me.theDataSet = New DataSet()
 
Try
Me.theOleDbCommand.Connection.Open()
Catch ex As Exception
End Try
 
End Sub
 
Public Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
 
FetchExcelData() ' Here data is fetched from Excel continuously using timer1_tick event
 
End Sub
 
Public Sub FetchExcelData()
 
Try
Me.theDataSet.Clear()
Me.theOleDbDataAdapter.Fill(theDataSet)
Me.theDataGridView.DataSource = theDataSet.Tables(0).DefaultView
Me.theOleDbDataAdapter.Dispose()
Catch ex As Exception
End Try
 
GC.Collect()
GC.WaitForPendingFinalizers()
 
End Sub
 
End Class
----------------------------------------------
GeneralRe: Can I read Opened Excel file continuosly?membersmramesh15 Jan '08 - 12:10 
Hi,
 
I finally realize that my problem was due to some bug in Excel and ADO memory Leak from this article below:
 
http://support.microsoft.com/kb/319998
 
Title:
BUG: Memory leak occurs when you query an open Excel worksheet by using ActiveX Data Objects (ADO)
 
Thanks
Ramesh
QuestionMixed Field issue?memberEdwardQ28 Nov '07 - 6:30 
Using the Microsoft.ACE.OLEDB have the same issue as using the Jet Driver with Mixed Fields?
 
I was writing a program that was reading a .xls (2003) file using the Jet Driver. The issue I found was if the a field (column) had both Numbers and Text. It looked at the 1st 8 rows by default to determine the field type. If the column had mostly numbers it set the field type as Number and returned NULL for the Text fields.
 


AnswerRe: Mixed Field issue?memberSarafian29 Nov '07 - 1:52 
We had the same problem. I sure would like to know whether i has been fixed.
GeneralRe: Mixed Field issue?memberMKauffman29 Nov '07 - 6:34 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel\@TypeGuessRows=0
 
A value of 0 will result in a scan of all the rows, whereas any other number n will result in a scan of the first n rows.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 28 Nov 2007
Article Copyright 2007 by Mihadh
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid