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?
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
.csprojfile. To force 32-bit, use:and to force 64-bit:
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:
What if you don't have the
Microsoft.ACE.OLEDB.12.0provider in either environment? If you can convert your.xlsxfile to an.xlsfile, you could use theMicrosoft 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
PlatformTargettox86(32-bit) as above. Then, edit the connection string to use the older provider: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:
NB. I found that in order to update data I needed to remove the
IMEX=1value from the connection string, per this answer.If you must use an
.xlsxfile, 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:
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.