C# – Read from Excel using OleDb in a Windows Service

cexcel

Disclaimer: I know this is a bad way to do things. It is the only option we have with our client.

Problem:

We need to read data from an Excel file every x amount of time. The data is constantly changing via a 3rd party Excel plug in. The environment for the application is Windows XP, SP1 and .Net 2.0. No upgrading the OS to SP2/3 or upgrading the .Net Framework. Again, this is all per customer parameters.

Here is current code we have:

String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Settings.ReutersFilePath + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
using (OleDbConnection objConn = new OleDbConnection(sConnectionString))
{
    try
    {
        objConn.Open();
        _dataSet = new DataSet();
        OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + ConfigurationManager.AppSettings["Excel.WorksheetName"] + "$]", objConn);
        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
        objAdapter1.SelectCommand = objCmdSelect;
        objAdapter1.Fill(_dataSet);
        _dataTable = _dataSet.Tables[0];
        objConn.Close();

        // Persists new data to a database.
        UpdateSQL();
    }
    catch (Exception ex) { }
    finally
    {
        _isCurrentlyProcessing = false;
        if (objConn != null && (objConn.State != ConnectionState.Broken || objConn.State != ConnectionState.Closed))
        {
            objConn.Close();
        }
    }
}

This code works when running from console or a Windows form, but when we run it from a Windows service, it cannot access the Excel file. Is there a limitation in XP w/SP1 that doesn't allow interaction with desktop applications like there is in Vista? Can this be done from a service? The reliability of running this from a service is much needed from the client.

Edit:

The service is running as LocalSystem.

Edit #2:

The error I get when running from a service is: The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.

The Excel file IS open on the desktop, but it has to be open for it to get updates from the 3rd party application.

Best Answer

In addition to @sontek's answer.

[only applicable If you are the owners/developers of the Spreadsheet in question...]

You may find it easier to work with a "data push" model rather than a "data pull" model. It's usually an easier programming model to push the data via an excel macro directly into your data store, based upon some event from your plug-in. this is often a much better scenario than a service polling on a timer.

Related Topic