SIGN UP MEMBER LOGIN:    
ARTICLE

Code Snippet for Fetching Data from Excel Using ADO.Net

Posted by Dhananjay Kumar Articles | ADO.NET in C# June 06, 2011
How to use code snippet for fetching data from Excel using ADO.Net.
Reader Level:


Today one of my team members asked me a very simple yet very important question:

"How could we fetch Excel Records using ADO.Net? Could you give me code snippet of same? "

I replied to him; it is pretty possible using OledDbConnection.

I told him to add the following reference.

I gave him the following straightforward code snippet. This function is:

  1. Returning DataTable
  2. Reading XLS file called YourFile.xls from F Drive.
  3. Reading Sheet1

public static  DataTable  GetItemsFromExcel1()
       {

                      DataTable dt = new DataTable();
 
           OleDbConnection excelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;"
                                                + @"Data Source=F:\YourFile.xls;"
                                                + @"Extended Properties=""Excel
8.0;HDR=Yes;IMEX=1;"""
);
 
           excelConnection.Open();
           try
           {
               OleDbDataAdapter dbAdapter =
                   new OleDbDataAdapter
                       ("SELECT * FROM [Sheet1$]", excelConnection);
               dbAdapter.Fill(dt);
           }
           finally
           {
               excelConnection.Close();
           }
 
return dt;
}


After using this function in his code, he was very happy and paid my coffee bill...

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks, Great tip!

Posted by Randy Howe Jun 08, 2011

Soorry for ths Inconvinence ... You can igonore first two lines of the function. We are not using that to read the Excel file. Thanks

Posted by Dhananjay Kumar Jun 08, 2011

What purpose does the lstItems and Items type serve and where is the definition of the Items type?

Posted by Randy Howe Jun 08, 2011

Nice solution..to ur team members and fr the community..

Posted by Shirsendu Nandi Jun 06, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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. Visit DynamicPDF here
Become a Sponsor