0

I have an Excel .xlsx file. I want to read data from the file and write data back to the file; no graphics, equations, images, just data.

I tried connecting using the types at System.Data.OleDb:

using System.Data.OleDb;

var fileName = @"C:\ExcelFile.xlsx";
var connectionString =
    "Provider=Microsoft.ACE.OLEDB.12.0;" +
    $"Data Source={fileName};" +
    "Extended Properties=\"Excel 12.0;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";

using var conn = new OleDbConnection(connectionString);
conn.Open();

but I get the following error:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

I know that I can install the Microsoft Access Database Engine 2016 Redistributable, but I want to do this without installing additional software.

How can I do this?

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
Hazem Elamir
  • 51
  • 1
  • 8
  • 1
    Does this answer your question? ['Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine](https://stackoverflow.com/questions/6649363/microsoft-ace-oledb-12-0-provider-is-not-registered-on-the-local-machine) – Zev Spitz Mar 03 '21 at 14:00
  • no, I don't need any plugin or extra installed files, I need to know how to setup the connection by my own code – Hazem Elamir Mar 03 '21 at 18:31
  • You want to reverse engineer the entire driver? It's some 50 MB of code... The closest you could come would be to check if you have the driver installed and you're using the wrong bit-ness; or maybe you could use an older version of the driver which is installed. – Zev Spitz Mar 03 '21 at 18:37
  • no, I could not do reverse engineer the entire driver of course, I think driver handle too many cases or options, I thought ACE connection can be setup with few lines of code – Hazem Elamir Mar 03 '21 at 19:32
  • It can be set up in a few lines of code ([example](https://stackoverflow.com/a/13719813/111794)), but **you need the appropriate driver**; without either trying to install the missing driver, or trying to use an alternate driver, your only options are to 1. reverse engineer the entire driver and ADODB system, or 2. use the .NET file reading, extraction, and XML parsing capabilities to extract data from this file. – Zev Spitz Mar 03 '21 at 19:35
  • second option looks to be easy and nice, can you give my the start, thanks in advance – Hazem Elamir Mar 03 '21 at 19:52
  • The second option only looks easy in comparison to the first option; not because it is objectively easy, simple or nice. You need to know the internal file structure of a `.xlsx` file -- which files go where; which file contains the data you are looking for; and what the structure of the XML used to define the data. All told, it's very nearly as complex and brittle as actually reverse-engineering the provider. // Do you keep your version of Windows up-to-date? Are you using a recent version of your browser? You should look at this installation in the same light. – Zev Spitz Mar 03 '21 at 21:22
  • I have rename .xlsx to .zip and i found that its a collection .xml files I think editing xml files is more easier than setup connection by code although I'm still want to learn this some day way many thanks for help – Hazem Elamir Mar 04 '21 at 18:39
  • I've rewritten both the question and the answer; I think the intent is clearer now. If the edits don't meet with your approval, feel free to rollback or to comment. – Zev Spitz Apr 13 '21 at 18:44

1 Answers1

0

For starters, you may well have the driver already installed, but only for 32-bit programs, while your program is running under 64-bit (or vice versa, but that's less common).

You can force a specific environment in your .csproj file. To force 32-bit, use:

<PropertyGroup>
  <PlatformTarget>x86</PlatformTarget>
</PropertyGroup>

and to force 64-bit:

<PropertyGroup>
  <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

If the driver has been installed in the other environment, your code should connect successfully.

NB. You can list the available providers for the current environment using code like the following:

using System.Data;
using System.Data.OleDb;
using System.Linq;
using static System.Console;

var oleEnum = new OleDbEnumerator();
var data =
    oleEnum.GetElements()
        .Rows
        .Cast<DataRow>()
        .Select(row => (
            name: row["SOURCES_NAME"] as string,
            descr: row["SOURCES_DESCRIPTION"] as string
        ))
        .OrderBy(descr => descr);
foreach (var (name, descr) in data) {
    WriteLine($"{name,-30}{descr}");
}

What if you don't have the Microsoft.ACE.OLEDB.12.0 provider in either environment? If you can convert your .xlsx file to an .xls file, you could use the Microsoft Jet 4.0 OLE DB Provider, which has been installed in every version of Windows since Windows 2000 (only available for 32-bit).

Set the PlatformTarget to x86 (32-bit) as above. Then, edit the connection string to use the older provider:

using System.Data.OleDb;

var fileName = @"C:\ExcelFile.xls";
// note the changes to Provider and the first value in Extended Properties
var connectionString =
    "Provider=Microsoft.Jet.OLEDB.4.0;" +
    $"Data Source={fileName};" +
    "Extended Properties=\"Excel 8.0;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";

using var conn = new OleDbConnection(connectionString);
conn.Open();

Once you have an open OleDbConnection, you can read and write data using the standard ADO .NET command idioms for interacting with a data source:

using System.Data;
using System.Data.OleDb;

var ds = new DataSet();
using (var conn = new OleDbConnection(connectionString)) {
    conn.Open();

    // assuming the first worksheet is called Sheet1

    using (var cmd = conn.CreateCommand()) {
        cmd.CommandText = "UPDATE [Sheet1$] SET Field1 = \"AB\" WHERE Field2 = 2";
        cmd.ExecuteNonQuery();
    }

    using (var cmd1 = conn.CreateCommand()) {
        cmd1.CommandText = "SELECT * FROM [Sheet1$]";
        var adapter = new OleDbDataAdapter(cmd);
        adapter.Fill(ds);
    }
};

NB. I found that in order to update data I needed to remove the IMEX=1 value from the connection string, per this answer.


If you must use an .xlsx file, and you only need to read data from the Excel file, you could use the ExcelDataReader NuGet package in your project.

Then, you could write code like the following:

using System.IO;
using ExcelDataReader;

// The following line is required on .NET Core / .NET 5+
// see https://github.com/ExcelDataReader/ExcelDataReader#important-note-on-net-core
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

DataSet ds = null;
using (var stream = File.Open(@"C:\ExcelFile.xlsx", FileMode.Open, FileAccess.Read)) {
    using var reader = ExcelReaderFactory.CreateReader(stream);
    ds = reader.AsDataSet();
}

Another alternative you might consider is to use the Office Open XML SDK, which supports both reading and writing. I think this is a good starting point -- it shows both how to read from a given cell, and how to write information back into a cell.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
  • Dear, I will use the code in my question to read data from excel file, but that code give me error 'microsoft.ace.oledb.12.0 is not registered on the local machine' , i need to know how to fix this error msg from my application with programing, not manually and not by installing any plugins – Hazem Elamir Mar 03 '21 at 18:44
  • @user4773407 I suppose if you really wanted to you could read the Excel file from disk, extract it as a ZIP file to the disk, read the resultant XML files, and extract the data that way. (Apparently you don't even want to use the OpenXML SDK.) I mean, how far [do you want to go](https://xkcd.com/676/) to avoid installing anything? Do you want to write assembler? – Zev Spitz Mar 03 '21 at 19:29
  • i was looking for to read data from excel file and write to it again, read sheets names and columns in each sheet, just read write, not equations or graphs or edit presentation of the cells – Hazem Elamir Mar 03 '21 at 19:38
  • @user4773407 And the approach you've taken -- connecting using OLEDB and ADO.NET will give you just that. But it relies on **being able to use the relevant provider** -- the **Microsoft.ACE.OLEDB.12.0** provider -- which means the provider needs to be installed, and in the appropriate bit-ness for your code. – Zev Spitz Mar 03 '21 at 19:41
  • I'm not sure what ( bit-ness ) mean, so, is there is any other approach to achieve what I'm looking for without installing any extra plugins? – Hazem Elamir Mar 03 '21 at 19:49
  • @user4773407 Bit-ness in this context means that the provider can be installed under 32-bit, in which case only programs running under 32-bit can use it; or under 64-bit, in which case only programs running under 64-bit can use it. (The provider can be installed in both.) – Zev Spitz Mar 03 '21 at 20:13