Reading Excel Spreadsheets with C# and ADO.Net

How to read and write to Excel Spreadsheets with C# using ADO.Net and Microsoft Office data connectors for OleDb with examples.

By Tim Trott | C# ASP.Net MVC | April 2, 2008

Microsoft .Net provides various methods to interact with Microsoft Office programs through the use of ADO.Net. This tutorial will look at the methods and techniques for reading from and writing to Excel spreadsheets with C# ADO.Net.

Reading Excel Spreadsheets Using ADO.Net and OleDB Provider

We can use the in-built OleDB provider for .Net to access Excel .xls spreadsheets, but before we do so, they need a little preparation. You can optionally create a Named Range to identify the table name, we also need column headings so if the spreadsheet does not contain column headings then you will need to add them.

Creating a Named Range in Excel

  1. With the spreadsheet open, select the data you wish to include in the query, including headings.
  2. Select the Insert Menu, then Name and select Define....
  3. Enter a name for the table and click Add.
  4. Close the dialogue and save the workbook.
Excel OLEDB
Excel OLEDB

Reading Excel Spreadsheets with C# ADO.Net

I am just going to create a simple console application that will run through all the customers and display them on the screen. The code itself is pretty straightforward, instead of SqlConnection, SqlCommand etc... we are using OleDbConnection and OleDbCommand.

C#
using System;
using System.Data.OleDb;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main()
    {
      string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:customers.xls; Extended Properties=Excel 8.0;";

      / Select using a Named Range
      string selectString = "SELECT * FROM Customers";

      / Select using a Worksheet name
      string selectString = "SELECT * FROM [Sheet1$]";

      OleDbConnection con = new OleDbConnection(connectionString);
      OleDbCommand cmd = new OleDbCommand(selectString,con);

      try
      {
        con.Open();
        OleDbDataReader theData = cmd.ExecuteReader();
        while (theData.Read())
        {
          Console.WriteLine("{0}: {1} ({2}) - {3} ({4})", theData.GetString(0),theData.GetString(1),theData.GetString(2),theData.GetString(3),theData.GetString(4));
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally
      {
        con.Dispose();
      }
    }
  }
}

Updating Excel Spreadsheets and Inserting Data with SQL

You can update records and insert data using regular SQL commands and execute the command through OleDb.

C#
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:customers.xls; Extended Properties=Excel 8.0;";
string selectString = "INSERT INTO Customers VALUES('12345', 'Acme Inc', 'Acme Way, CA', 'Testy McTest', '01234-987654')";

OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(selectString, con);

try
{
  con.Open();
  cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}
finally
{
  con.Dispose();
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 12 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. NM

    On Wednesday 11th of January 2012, Nirav Modi said

    I am given range for only one cell where data is "date". But it's not give me proper output. Please reply me ASAP. Thanks

  2. RH

    On Thursday 26th of November 2009, Rhodri said

    Any idea how the Jet OleDB commands can recognise dynamic named ranges? I can't get Jet to recognise them, although a static range like your example works fine.

    Thanks

  3. CH

    On Thursday 17th of September 2009, Chris said

    The only problem I am having with reading an Excel file this way, is that it always returns my rows & fields in alphabetical order! I want the select statement to return everything in the order it was entered in the Excel file. Is there any way to prevent the provider from "automatically" ordering the columns & rows in alphabetical order? To see what I'm talking about, change the Account Number in your first row from "00001" to "10000" and watch it appear at the end of the result set 'all of a sudden'.

  4. SH

    On Saturday 30th of May 2009, Sheetal said

    ===The code below works===

    C#
    using System.Data.OleDb;
    
    public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Documents and SettingsuserDesktopBook1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
    
            string selectString = "SELECT * FROM Customers";
           selectString = "SELECT * FROM [Sheet1$]";
    
          OleDbConnection con = new OleDbConnection(connectionString);
          OleDbCommand cmd = new OleDbCommand(selectString,con);
          con.Open();
          try
          {
            /to read the data
            OleDbDataReader theData = cmd.ExecuteReader();
              while(theData.Read())
              {
                  Response.Write(theData[0].ToString()+" ");
                  Response.Write(theData[1].ToString());
                  Response.Write("");
              }
              cmd.Dispose();
    
             /To insert the data
    
             cmd = new OleDbCommand("insert into [Sheet1$]  values(103,"Company G","Address 7")", con);
            cmd.ExecuteNonQuery();
    
             
          }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
  5. CA

    On Monday 27th of April 2009, Chetankumar Akarte said

    Hi,

    If you want to read data from a .xlsx file, you have to use Microsoft.ACE.OLEDB.12.0 as the provider. This is the new Access database engine OLE DB driver and is also capable of reading Excel 2003. Use it to read xlsx (Excel 2007) data.

    Get more info on Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET here...

    http://www.tipsntracks.com/100/read-and-display-data-from-an-excel-file-xsl-or-xlsx-in-aspnet.html

    Thanks & Regards
    Chetankumar Akarte

  6. BI

    On Thursday 19th of March 2009, biham said

    HI There
    I am Getting the following error. I am using Vs 2008 and Excel 2007. I know the path and spelling are all correct any help will be greatly appreciated

    string The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sur
    e the object exists and that you spell its name and the path name correctly.
    Press any key to continue . . .

    1. Tim Trott

      On Wednesday 25th of March 2009, Tim Trott  Post Author replied

      Hello,

      Sheet1$ refers to the sheet name. If you have changed the sheet name then you must update the code accordingly. Also, I have not tried this with Excel 2007 which uses a different file format. If you are not doing so already you may wish to try exporting as Excel 2000.

      Hope that helps

  7. Tim Trott

    On Friday 13th of February 2009, Tim Trott  Post Author said

    viranjuda, It's difficult to diagnose a problem without seeing the code.

    There are several things that may cause this error including file permissions, file location (local or network), are you calling the code from a console application or ASP.Net? What is the query you are trying to execute?

    If you could provide more information we may be better able to assist.

  8. VI

    On Wednesday 11th of February 2009, viranjuda said

    System.Data.OleDb.OleDbException: Operation must use an updateable query.
    at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARA
    MS dbParams, Object& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Ob
    ject& executeResult)
    at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behav
    ior, String method)
    at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
    at ExcelConn.ExcelConnection.ExcelInsertPermintaan(String sNo, String sAppCod
    e, String sTglMinta, String sNmDebitur, String sAlamat, String sNomor, String sN
    oKTP_Passport, String sDatiII, String sUser, String sTglLahir, String sKodePos,
    String sNPWP, String sTempatLahir, String sDIN, String sNmAlias, String sNoPassp
    ort) in D:AJDSMegaConsoleTryExcelConnIExcelConnIConnectionForExcel.cs:li
    ne 30
    at ExcelConn.MySQLConnection.MySQLConnector() in D:AJDSMegaConsoleTryEx
    celConnIExcelConnIConnectionForMySQL.cs:line 72
    at ExcelConn.Program.Main(String[] args) in D:AJDSMegaConsoleTryExcelCo
    nnIExcelConnIProgram.cs:line 16

    Does anybody know that this exception means?

  9. Tim Trott

    On Monday 19th of January 2009, Tim Trott  Post Author said

    This code was built and compiled on Windows XP SP3 with Visual Studo 2005 and Office 2000 installed. It has also been tested on a fresh copy of Windows XP with SP2 and .Net framework 2, MS Office is not installed.

    Create a standard console application with the above code, no additional references are required, System, System.Data and System.Xml automatically referenced.

    @anonymous, please can you provide any more details of your error (project type, references, visual studio version etc..)

    @Pratap, please could you also provide some more details, such as the error message?

  10. On Thursday 15th of January 2009, said

    Error 2 The type 'System.ComponentModel.Component' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. D:IdeasCSExplorerExplorer.cs 38 13 Explorer.

    I'm getting this error message, hat .Net environment you are supose to have, what refrences, etc. very amateurish and not useful at all.

  11. PR

    On Saturday 9th of August 2008, Pratap said

    how to get the connection string in Console Application.

    It shows like I don't have proper OLE db.

    Since whatever You have used in code may be for your system. My system settings are different. So how can I get the Connection string in my system for my project.