Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Reading and Writing Excel using OLEDB

Rate me:
Please Sign up or sign in to vote.
4.61/5 (55 votes)
28 Oct 20044 min read 881.9K   26.5K   228   98
Shows how to use OLEDB to read from and write to Excel workbook files.

Application screenshot

Introduction

This project contains an ExcelReader class. This class reads Excel files by using the OLEDB driver. Many articles already have been written about it. This class however is an easy way to read and write Excel values. It's possible to read or write single values or data tables.

However, due to restrictions in the Excel driver, it is not possible to delete rows from a table. Updating a empty range is also not an option. It's possible to read an range and updating or inserting an existing range. Excel has his own way of datatatyping the column. DaberElay made a response according to my article with:

How does it happen?

Apparently, the engine reads the first 8 cells of each column and check it's data type. if most of the first 8 cells are int / double, the problem remains.

Is this solveable ? Yes and No. We can ask that the engine will check more than 8 cells ( setting the registry value

HKLM\Software\Microsoft\Jet\4.0\Engines\Excel\TypeGuessRows to 0 which will check the first 16,000 rows, and holds a small performance hit ).

But if all your first 16000 rows are numeric and only then you have textual values, you are in a problem.

Another thing we can do is set the TypeGuessRows to 1,and set the connection string's extended property - HDR to No, so if you always have headers in your excel it will read the first row and decide that its a text field.

Notice however, that this means you will have to create the column names from the unnecessary extra first row you now have in your rows.

If the OLEDB solution does not fit your needs, you may buy a component for it. There are some components to read or wrrite the Excel files without MS Excel and are able to edit.

Here are some ideas.

Background

For a project, I needed to read and write MS Excel-files on a web server. The MS Excel file would be uploaded and be read on the server into a SQL Server database.

Normally, I would have used the XML grammar Microsoft has published for the web. Unfortunately, this is a grammar supported by MS Excel 2002 or higher. It makes it easier to make a component to modify and read Excel workbooks. Only in my projects, the clients always use older software like MS Excel '97 that do not support this XML. I also like to choose a solution which uses just one version of Excel 2002 with a programmed converter class. Only this process will run on a web server where MS Office and its components are not scalable and not allowed. Also read what Microsoft says about it. So, I started a class that uses the OLEDB driver that can do some primary tasks with the uploaded Excel file.

Using the code

The demo form uses the following code to initialize the ExcelReader class:

C#
exr = new ExcelReader();
_dt = new DataTable("par");
exr.KeepConnectionOpen =true;
exr.ExcelFilename = _strExcelFilename;
exr.Headers =false;
exr.MixedData =true;
exr.SheetName = this.txtSheet.Text;
exr.SheetRange = this.txtRange.Text;
exr.SetPrimaryKey(0);
_dt = exr.GetTable();

First, create a new instance of this class. Also declare a DataTable. I prefer it to have it as a private class variable. After updating a grid, I will use the table variable to update the table with the ExcelReader class. The keepconnection open property keeps the connection open after an ExcelReader operation, and saves time. The header options mean, if there is a rowheader row in MS Excel to explain the columndata. The MixedData property uses the IMEX option (0=export, 1=import, 2=linked). By default, the property is true and IMEX =2. If false, there is no IMEX option in the connection string. Also set the sheetname and the range.

The primary key is needed to be able to update the Excel sheet. It now supports just one primary key, but the class can be extended. If the table has no primary key, the DataAdapter will not work. The Excel driver does not discover primary keys, so it must be set manually. The DataColumnNumber 0 is the first column of the range set. The GetTable() returns the data of the requested Excel range in a DataTable. Updating of the range in the Excel file itself can be done with the SetTable(DataTable) method. Just download the demo and take a look.

How it's done

First, set the connection:

C#
private string ExcelConnection()
{
    return
        @"Provider=Microsoft.Jet.OLEDB.4.0;" + 
        @"Data Source=" + _strExcelFilename  + ";" + 
        @"Extended Properties=" + Convert.ToChar(34).ToString() + 
        @"Excel 8.0;"+ ExcelConnectionOptions() + Convert.ToChar(34).ToString(); 
}
#endregion

Open the connection:

C#
_oleConn = new OleDbConnection(ExcelConnection());
_oleConn.Open();

And just make a OledbCommand to select with a text like select * from [sheetname$[range].

C#
_oleCmdSelect =new OleDbCommand(
    @"SELECT * FROM [" 
    + _strSheetName 
    + "$" + _strSheetRange
    + "]", _oleConn);

Fill the table with the select command to retrieve the data actually:

C#
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable dt = new DataTable(strTableName);
oleAdapter.FillSchema(dt,SchemaType.Source);
oleAdapter.Fill(dt);

Updating the table:

First set the primary key(s). Then call the update method to update the excel table. Try in the demo to update an empty range! An error will occur.
C#
if (this._intPKCol>-1)
{
    int[] intPKCols = new int[]  { _intPKCol};
    _exr.PKCols = intPKCols;
}
_exr.SetTable(_dt); 

History

  • 1.1 Fixed some bugs and added some functions
    • The Excel sheetnames can be retrieved with a method call.
    • Functions to retrieve the real excel column names or the columnnumbers.
    • Fixed some bugs in connection string and SetSheetQueryAdapter.
  • 1.0 Initial ExcelReader class.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Netherlands Netherlands
I am Dieder Timmerman. I work as Senior Software Engineer at Ordina. I have MCSD.

Comments and Discussions

 
PraiseStill works with Excel 365 VS15 (64-Bit) Pin
mcshjs4-Aug-20 23:41
mcshjs4-Aug-20 23:41 
PraiseThank you, it is very useful Pin
IsakMtz25-Mar-20 9:19
IsakMtz25-Mar-20 9:19 
QuestionHow to save this imported data in SQlite database quickly/ efficiently Pin
nick_bkk2-Dec-16 17:46
nick_bkk2-Dec-16 17:46 
SuggestionUsing OLEDB (MS Query) in Excel Pin
Member 1176681125-Nov-15 1:08
Member 1176681125-Nov-15 1:08 
QuestionSee also this: Pin
dietmar paul schoder29-Jul-14 5:23
professionaldietmar paul schoder29-Jul-14 5:23 
QuestionMap1.xls Pin
@arka18-Nov-13 11:04
@arka18-Nov-13 11:04 
GeneralMy vote of 4 Pin
liuchao30522-Apr-13 19:33
liuchao30522-Apr-13 19:33 
BugBUG in ColNumber function Pin
lucagabrielli17-Jul-12 22:39
lucagabrielli17-Jul-12 22:39 
Hi, the ColNumber function have a bug and not work if you try to select a range starting with two value row ( es. A16:B100 ), the function try to convert the first number of the rows numbers as a column, here my contribute
byez

C#
public int ColNumber(string strCol)
{
    strCol = strCol.ToUpper();
    int intColNumber=0;
    int letter_num = 0;
    foreach ( char c in strCol )
    {
        if ( Char.IsLetter(c) )
            letter_num++;
    }

    if (letter_num > 1)
    {
        intColNumber = Convert.ToInt16(Convert.ToByte(strCol[0])-65);
        intColNumber += Convert.ToInt16(Convert.ToByte(strCol[1])-64)*26;
    }
    else
        intColNumber = Convert.ToInt16(Convert.ToByte(strCol[0])-65);
    return intColNumber;
}

GeneralMy vote of 5 Pin
Carlos Bordachar5-Jul-12 6:46
Carlos Bordachar5-Jul-12 6:46 
QuestionMy vote of 5 Pin
jp2code18-Jul-11 11:13
professionaljp2code18-Jul-11 11:13 
GeneralRegarding form controls in excel Pin
Sundeep Ganiga18-Mar-10 20:53
Sundeep Ganiga18-Mar-10 20:53 
Generalreading numbers with leading zero's Pin
FreddieH8516-Aug-09 23:36
FreddieH8516-Aug-09 23:36 
QuestionInserting takes too much time Pin
adamshuv30-Apr-09 1:16
adamshuv30-Apr-09 1:16 
Generaldata retrieve from Excel Pin
viki24627-Apr-09 17:19
viki24627-Apr-09 17:19 
GeneralRe: data retrieve from Excel Pin
guyanese4life222-Jun-10 5:51
guyanese4life222-Jun-10 5:51 
GeneralRead Formula Pin
mrtom8418-Nov-07 11:57
mrtom8418-Nov-07 11:57 
GeneralRange Problem Large Sheet Name Pin
rmoreirao24-Oct-07 4:34
rmoreirao24-Oct-07 4:34 
GeneralGood Job Pin
Yasin HINISLIOGLU24-Jul-07 4:01
Yasin HINISLIOGLU24-Jul-07 4:01 
GeneralFixed BUG in 'GetExcelSheetNames' Pin
Cabbi18-May-07 2:11
Cabbi18-May-07 2:11 
NewsFixed BUG in 'SetValue' Pin
Cabbi17-May-07 21:00
Cabbi17-May-07 21:00 
Questionhow to populate column in this Pin
Ravi shuk11-Apr-07 3:00
Ravi shuk11-Apr-07 3:00 
Generalhelp me plzzz Pin
Ravi shuk10-Apr-07 2:15
Ravi shuk10-Apr-07 2:15 
Generalproblem with no of columns in excel Pin
Ravi shuk10-Apr-07 2:13
Ravi shuk10-Apr-07 2:13 
Generalproblems with no of columns in Excel Pin
Ravi shuk9-Apr-07 20:51
Ravi shuk9-Apr-07 20:51 
GeneralSetSheetQueryAdapter bugs Pin
YI Tan12-Mar-07 17:34
YI Tan12-Mar-07 17:34 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.