Oledb provider for excel 64 bit

Содержание

  1. Импорт данных из Excel в Microsoft SQL Server на языке T-SQL
  2. Введение
  3. Импорт данных из Excel 2003 (файл xls) в Microsoft SQL Server x86
  4. Шаг 1 – Проверяем наличие провайдера Microsoft.Jet.OLEDB.4.0 на SQL Server
  5. Шаг 2 – Предоставление прав пользователю на временный каталог
  6. Шаг 3 – Включаем распределенные запросы на SQL Server
  7. Шаг 4 – Выполняем SQL запрос, обращение к файлу Excel
  8. Импорт данных из Excel 2007 и выше (файл xlsx) в Microsoft SQL Server x86
  9. Шаг 1 – Проверяем наличие провайдера Microsoft.ACE.OLEDB.12.0 на SQL Server
  10. Шаг 2 – Установка провайдера Microsoft.ACE.OLEDB.12.0 (32-bit)
  11. Шаг 3 – Предоставление прав пользователю на временный каталог
  12. Шаг 4 – Включаем распределенные запросы на SQL Server
  13. Шаг 5 – Настройка провайдера Microsoft.ACE.OLEDB.12.0
  14. Шаг 6 – Выполняем SQL запрос, обращение к файлу Excel
  15. Импорт данных из Excel (любые файлы) в Microsoft SQL Server x64
  16. Шаг 1 – Проверяем наличие провайдера Microsoft.ACE.OLEDB.12.0 на SQL Server
  17. Шаг 2 – Установка провайдера Microsoft.ACE.OLEDB.12.0 (64-bit)
  18. Шаг 3 – Включаем распределенные запросы на SQL Server
  19. Шаг 4 – Настройка провайдера Microsoft.ACE.OLEDB.12.0
  20. Шаг 5 – Выполняем SQL запрос, обращение к файлу Excel
  21. Подведение итогов
  22. Excel connection strings
  23. .NET libraries
  24. OLE DB providers
  25. ODBC drivers
  26. Wrappers and others
  27. CData ADO.NET Provider for Excel
  28. Standard
  29. No headers in Excel sheet
  30. Caching data
  31. Caching data and metadata
  32. Cached data only / Offline mode
  33. Using an External Cache Provider
  34. Empty cells always NULL
  35. Empty cells always empty string
  36. Suppress formula calculation errors
  37. Read «tilted sheets», where rows are headers and columns are rows
  38. Do not use formulas, only values
  39. Microsoft ACE OLEDB 12.0
  40. Xlsx files
  41. Treating data as text
  42. Xlsb files
  43. Xlsm files
  44. Excel 97-2003 Xls files with ACE OLEDB 12.0
  45. Microsoft Jet OLE DB 4.0
  46. Standard (Excel)
  47. Standard alternative
  48. .NET Framework Data Provider for OLE DB
  49. Use an OLE DB provider from .NET

Импорт данных из Excel в Microsoft SQL Server на языке T-SQL

Microsoft SQL Server позволяет встроенными средствами языка T-SQL в SQL запросе импортировать данные из файла Excel в базу данных. Сегодня я подробно расскажу, как это делается, какие условия необходимо выполнить, чтобы эта операция проходила успешно, расскажу про особенности импорта для самых распространённых случаев конфигураций SQL сервера и приведу конкретный порядок действий и практические примеры.

Начну я с того, что импортировать данные из Excel в Microsoft SQL Server можно с помощью «Распределенных запросов» и с помощью «Связанных серверов». Это, скорей всего, Вы уже знаете, так как я уже не раз писал об этом (ссылки на соответствующие материалы указаны чуть выше).

Обратиться к файлу Excel и импортировать данные в Microsoft SQL Server можно с помощью T-SQL инструкций OPENDATASOURCE, OPENROWSET или OPENQUERY.

Однако в вышеупомянутых статьях я упустил несколько важных моментов, одним из которых является то, что у всех конфигурация SQL сервера разная, за счет чего у многих возникают различные проблемы и появляются ошибки во время выполнения распределенных запросов и обращений к связанным серверам. Также я описывал способ загрузки данных из Excel, который на сегодняшний день уже устарел, поэтому сегодня я постараюсь дать Вам немного больше информации о том, как импортировать данные из файла Excel в Microsoft SQL Server на языке T-SQL.

Введение

Итак, как я уже сказал, очень важную роль здесь играет конфигурация SQL сервера, в частности, какая версия сервера установлена, x86 или x64.

Если говорить о последних версиях Microsoft SQL Server 2016-2019, то они только x64 и устанавливаются на 64-разрядные версии Windows.

Исходя из этого я разделю статью на несколько частей, в каждой из которых я расскажу про особенности импорта данных из Excel для самых распространённых случаев конфигураций и приведу конкретный порядок действий.

Для того чтобы быстро узнать, какая версия SQL Server установлена у Вас на компьютере, можете выполнить простой SQL запрос

Обращение к файлу Excel и, соответственно, импорт данных в Microsoft SQL Server происходит с помощью специальных провайдеров (поставщиков). Для работы с Excel в Microsoft SQL Server обычно используются:

Во всех примерах ниже я буду посылать простой запрос SELECT на выборку данных из Excel файла, для того чтобы проверить доступ к данным в файле Excel. Чтобы осуществить импорт данных (загрузить данные в БД), Вы можете использовать любой удобный для Вас способ, например, конструкцию SELECT INTO или INSERT INTO.

Дополнительно рекомендовано закрывать файл Excel во время обращения к нему в распределенных запросах, а также указывать путь к файлу без пробелов (хотя современный SQL сервер умеет работать с пробелами).

Импорт данных из Excel 2003 (файл xls) в Microsoft SQL Server x86

Шаг 1 – Проверяем наличие провайдера Microsoft.Jet.OLEDB.4.0 на SQL Server

Первое, с чего нам нужно начать, это проверить, зарегистрирован ли провайдер Microsoft.Jet.OLEDB.4.0 на SQL Server, так как в данном случае необходимо использовать именно этот провайдер. Это можно сделать с помощью следующей SQL инструкции

В результирующем наборе данных должна присутствовать строка с Microsoft.Jet.OLEDB.4.0. Если такого провайдера нет, то скорей всего в системе нет установленного Excel 2003 и, соответственно, его нужно установить.

Шаг 2 – Предоставление прав пользователю на временный каталог

Особенностью распределённых запросов и работы со связанным серверами Excel в x86 версиях SQL Server является то, что независимо от имени какой учетной записи посылается SQL запрос к Excel, эта учетная запись должна иметь права на запись во временный каталог той учетной записи, под которой работает сама служба SQL Server.Так как поставщик OLE DB создает временный файл во время запроса во временном каталоге SQL Server, используя учетные данные пользователя, выполняющего запрос.

Таким образом, если служба SQL Server работает от имени или локальной, или сетевой службы, необходимо дать соответствующие права на временный каталог этих служб всем пользователям, которые будут посылать распределенные запросы и обращаться к связанному серверу Excel (если сервер работает от имени пользователя, который посылает SQL запросы, то такие права давать не требуется, они у него уже есть).

Это можно сделать с помощью встроенной утилиты командной строки icacls.

Например, для локальной службы команда будет выглядеть следующим образом.

Для сетевой службы

Вместо UserName укажите имя пользователя, который посылает запрос.

Шаг 3 – Включаем распределенные запросы на SQL Server

По умолчанию возможность использования распределённых запросов, в частности функций OPENDATASOURCE и OPENROWSET, в Microsoft SQL Server запрещена, поэтому данную возможность нужно сначала включить.

Она включается с помощью системной хранимой процедуры sp_configure, которая отвечает за системные параметры сервера. Нам необходимо параметру Ad Hoc Distributed Queries присвоить значение 1, для этого выполняем следующую SQL инструкцию.

Шаг 4 – Выполняем SQL запрос, обращение к файлу Excel

Ниже я приведу несколько вариантов обращения к файлу Excel (TestExcel.xls).

OPENROWSET

OPENDATASOURCE

Linked Server

Импорт данных из Excel 2007 и выше (файл xlsx) в Microsoft SQL Server x86

Шаг 1 – Проверяем наличие провайдера Microsoft.ACE.OLEDB.12.0 на SQL Server

Точно так же, как и в предыдущем примере, сначала проверяем, установлен ли у нас необходимый нам провайдер, в данном случае нам нужен Microsoft.ACE.OLEDB.12.0.

Шаг 2 – Установка провайдера Microsoft.ACE.OLEDB.12.0 (32-bit)

Если провайдера нет, то его необходимо установить.

Вот ссылка на скачивание провайдера

Выберите и скачайте файл, соответствующий архитектуре x86 (т.е. в названии без x64).

Шаг 3 – Предоставление прав пользователю на временный каталог

В данном случае также даем права на временный каталог локальной или сетевой службы всем пользователям, которые будут посылать SQL запросы к файлу Excel.

Используем все ту же утилиту командной строки icacls.

Для локальной службы

Вместо UserName укажите имя пользователя, который посылает запрос.

Шаг 4 – Включаем распределенные запросы на SQL Server

Включаем возможность использования OPENDATASOURCE и OPENROWSET на Microsoft SQL Server, повторюсь, что по умолчанию данная возможность отключена.

Шаг 5 – Настройка провайдера Microsoft.ACE.OLEDB.12.0

В данном случае дополнительно потребуется настроить провайдер Microsoft.ACE.OLEDB.12.0. Для этого включим следующие параметры провайдера (для отключения укажите 0 вместо 1).

Если не включать данные параметры, то, скорей всего, появится ошибка примерно следующего содержания

«Сообщение 7399, уровень 16, состояние 1, строка 25
Поставщик OLE DB «Microsoft.ACE.OLEDB.12.0» для связанного сервера «(null)» сообщил об ошибке. Поставщик не предоставил данных об ошибке.
Сообщение 7330, уровень 16, состояние 2, строка 25
Не удалось получить строку от поставщика OLE DB «Microsoft.ACE.OLEDB.12.0» для связанного сервера «(null)».»

Шаг 6 – Выполняем SQL запрос, обращение к файлу Excel

Примеры обращения к файлу Excel (TestExcel.xlsx).

OPENROWSET

OPENDATASOURCE

Linked Server

Импорт данных из Excel (любые файлы) в Microsoft SQL Server x64

Шаг 1 – Проверяем наличие провайдера Microsoft.ACE.OLEDB.12.0 на SQL Server

В данном случае мы также используем провайдер Microsoft.ACE.OLEDB.12.0, сначала проверяем, зарегистрирован ли он на сервере.

Шаг 2 – Установка провайдера Microsoft.ACE.OLEDB.12.0 (64-bit)

В случае, если провайдер не установлен, его необходимо скачать и установить.

Скачиваем файл x64.

Шаг 3 – Включаем распределенные запросы на SQL Server

Необходимость включения возможности использования распределенных запросов (OPENDATASOURCE и OPENROWSET) на Microsoft SQL Server x64 также есть, поэтому сначала включаем ее, выполнив точно такую же инструкцию.

Шаг 4 – Настройка провайдера Microsoft.ACE.OLEDB.12.0

В этом случае, скорей всего, настройка провайдера не потребуется, поэтому сначала сразу пробуем выполнить SQL запросы (обратиться к данным в Excel), и если возникает ошибка (все с тем же сообщением 7399 и 7330), то пробуем включить параметры AllowInProcess и DynamicParameters (для отключения укажите 0 вместо 1).

Шаг 5 – Выполняем SQL запрос, обращение к файлу Excel

Здесь используются точно такие же параметры в SQL запросах, что и в предыдущем примере. Для удобства продублирую их еще раз.

Примеры обращения к файлу Excel (TestExcel.xlsx).

OPENROWSET

OPENDATASOURCE

Linked Server

Подведение итогов

Ну и в заключение я сгруппирую действия, которые необходимо выполнять в зависимости от выпуска SQL Server (x68 или x64) и версии файла Excel (xls или xlsx), в одну таблицу, для Вашего удобства.

Действие / Настройка Импорт Excel 2003 (файл xls) в SQL Server x86 Импорт Excel 2007 (файл xlsx) в SQL Server x86 Импорт Excel (любые файлы) в SQL Server x64
Установка Excel 2003 Да Нет Нет
Установка провайдера Microsoft.ACE.OLEDB.12.0 Нет Да (x86) Да (x64)
Предоставление прав на временный каталог служб (если SQL сервер работает от имени служб) Да Да Нет
Настройка провайдера Microsoft.ACE.OLEDB.12.0 Нет Да Нет (по необходимости)
Параметры подключения в SQL запросах Microsoft.Jet. OLEDB.4.0 и Excel 8.0 Microsoft.ACE. OLEDB.12.0 и Excel 12.0 Microsoft.ACE. OLEDB.12.0 и Excel 12.0
Включение распределённых запросов на SQL Server Да Да Да

Заметка! Для комплексного изучения языка T-SQL рекомендую посмотреть мои видеокурсы по T-SQL, в которых используется последовательная методика обучения и рассматриваются все конструкции языка SQL и T-SQL.

На сегодня это все, удачи Вам в освоении языка T-SQL!

Источник

Excel connection strings

.NET libraries

OLE DB providers

ODBC drivers

Wrappers and others

CData ADO.NET Provider for Excel

Standard

Pseudo column names (A,B,C) are used instead.

Caching data

To retrieve data from the cache, add «#Cache» to the table name. For example, to query cached data from the «Sheet» table, execute «SELECT * FROM [Sheet#Cache]».

Caching data and metadata

The table metadata will also be cached instead of retrieving it from the data source. This improves connection performance. Read more here →

Cached data only / Offline mode

SELECT statements will always retrieve data from the cache. DELETE/UPDATE/INSERT statements is not allowed and will throw an exception.

Using an External Cache Provider

RSSBus drivers have the ability to cache data in a separate database such as SQL Server or MySQL instead of in a local file using the following syntax:

Cache Provider = Provider.Namespace; Cache Connection = ‘Connection String to Cache Database’;

Above is just an example to show how it works. It can be used both with «Auto Cache» and with «Cached Data Only / Offline Mode». Read more about using RSSBus Cache Provider in this article >>>

Empty cells always NULL

Empty cells always empty string

Suppress formula calculation errors

Do not use formulas, only values

Do not treat values starting with equals (=) as formulas during inserts and updates.

Excel File = C:myExcelFile.xlsx; Allow Formula = false;

Microsoft ACE OLEDB 12.0

Xlsx files

Connect to Excel 2007 (and later) files with the Xlsx file extension. That is the Office Open XML format with macros disabled.

Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:myFoldermyExcel2007file.xlsx; Extended Properties = «Excel 12.0 Xml; HDR = YES»;

«HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

Treating data as text

Use this one when you want to treat all data in the file as text, overriding Excels column type «General» to guess what type of data is in the column.

Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:myFoldermyExcel2007file.xlsx; Extended Properties = «Excel 12.0 Xml; HDR = YES; IMEX = 1»;

If you want to read the column headers into the result set (using HDR=NO even though there is a header) and the column data is numeric, use IMEX=1 to avoid crash.

To always use IMEX=1 is a safer way to retrieve data for mixed data columns. Consider the scenario that one Excel file might work fine cause that file’s data causes the driver to guess one data type while another file, containing other data, causes the driver to guess another data type. This can cause your app to crash.

Xlsb files

Connect to Excel 2007 (and later) files with the Xlsb file extension. That is the Office Open XML format saved in a binary format. I e the structure is similar but it’s not saved in a text readable format as the Xlsx files and can improve performance if the file contains a lot of data.

Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:myFoldermyBinaryExcel2007file.xlsb; Extended Properties = «Excel 12.0; HDR = YES»;

You can also use this connection string to connect to older 97-2003 Excel workbooks.

«HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

Xlsm files

Connect to Excel 2007 (and later) files with the Xlsm file extension. That is the Office Open XML format with macros enabled.

Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:myFoldermyExcel2007file.xlsm; Extended Properties = «Excel 12.0 Macro; HDR = YES»;

«HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

Excel 97-2003 Xls files with ACE OLEDB 12.0

You can use this connection string to use the Office 2007 OLEDB driver (ACE 12.0) to connect to older 97-2003 Excel workbooks.

Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:myFoldermyOldExcelFile.xls; Extended Properties = «Excel 8.0; HDR = YES»;

«HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

Microsoft Jet OLE DB 4.0

Standard (Excel)

Standard alternative

Try this one if the one above is not working. Some reports that Excel 2003 need the exta OLEDB; section in the beginning of the string.

OLEDB; Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:MyExcel.xls; Extended Properties = «Excel 8.0; HDR = Yes; IMEX = 1»;

«HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

«IMEX=1;» tells the driver to always read «intermixed» (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.

SQL syntax «SELECT [Column Name One], [Column Name Two] FROM [Sheet One$]». I.e. excel worksheet name followed by a «$» and wrapped in «[» «]» brackets.

«SELECT * FROM [Sheet1$a5:d]», start picking the data as of row 5 and up to column D.

Check out the [HKEY_LOCAL_MACHINESOFTWAREMicrosoftJet4.0EnginesExcel] located registry REG_DWORD «TypeGuessRows». That’s the key to not letting Excel use only the first 8 rows to guess the columns data type. Set this value to 0 to scan all rows. This might hurt performance. Please also note that adding the IMEX=1 option might cause the IMEX feature to set in after just 8 rows. Use IMEX=0 instead to be sure to force the registry TypeGuessRows=0 (scan all rows) to work.

If the Excel workbook is protected by a password, you cannot open it for data access, even by supplying the correct password with your connection string. If you try, you receive the following error message: «Could not decrypt file.»

.NET Framework Data Provider for OLE DB

Use an OLE DB provider from .NET

See the respective OLEDB provider’s connection strings options. The .net OleDbConnection will just pass on the connection string to the specified OLEDB provider. Read more here.

Источник

This OLE DB Provider is provided by Microsoft.
The main functionality of the provider is contained in the file ACEOLEDB.DLL.

Include «Provider=Microsoft.ACE.OLEDB.12.0» in the connection string to use this provider.

Description

This driver was first released with Office 2007. It is possible to use the Microsoft.ACE.OLEDB.12.0 to connect to old .xls (Excel 97-2003) workbooks as well. The driver is available in both 32 bit and 64 bit versions.

Please Note!
There are some reported problems with the «Microsoft Access Database Engine 2010 Redistributable» package that seems to arise when using 64 bit windows and 64 bit office 2010 or above.
The reported solution is to install the «2007 Office System Driver: Data Connectivity Components» instead.
Read more in this article.

Download

This OLE DB Provider, Microsoft ACE OLEDB 12.0, can be downloaded here.

Connection Strings

The Microsoft ACE OLEDB 12.0 provider can be used to connect to the following data sources by using the following connection string references:

ExcelExcel 97Excel 2000Excel 2002Excel 2003Excel 2007Excel 2010Excel 2013AccessAccess 97Access 2000Access 2002Access 2003Access 2007Access 2010Access 2013DBF / FoxProSharePoint

Introduction

This article describes the complete steps for Microsoft Excel data import to SQL Server using distributed queries technique.

The article describes the steps for all modern platforms:

  • Microsoft SQL Server 2005-2016 on the x86/x64 platform.
  • Microsoft Excel 2003-2016 files like *.xls, *.xlsx, *.xlsm, *.xlsb.

Bonus

You can develop amazing Microsoft Excel applications for working with Microsoft SQL Server using database development skills only!

Visit www.savetodb.com, download and install SaveToDB Add-In for Microsoft Excel.

That’s all!

Connect to tables, views, and stored procedures, edit the data and save it back to a database.

Add features to your Microsoft Excel applications step by step configuring apps via SQL.

Table of Contents

  • Introduction
  • The basics of Excel Data Import to SQL Server
  • Configuration steps for Excel data import to SQL Server
    • Install Microsoft.ACE.OLEDB.12.0 driver
    • Configure Ad Hoc Distributed Queries
    • Grant rights to TEMP directory
    • Configure ACE OLE DB properties
  • How-To: Import Excel 2003 to SQL Server x86
  • How-To: Import Excel 2007 to SQL Server x86
  • How-To: Import Excel 2003/2007 to SQL Server x64
  • Conclusion
  • See Also

The Basics of Excel Data Import to SQL Server

To import data from Microsoft Excel to SQL Server OPENROWSET and OPENDATASOURCE functions with OLE DB data source can be used.

The basic format for the Microsoft.Jet.OLEDB.4.0 provider is:

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;Database=C:excel-sql-server.xls', [Sheet1$])
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
  'Data Source=C:excel-sql-server.xls;Extended Properties=Excel 8.0')...[Sheet1$]

The basic format for the Microsoft.ACE.OLEDB.12.0 provider is:

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
  'Excel 12.0;Database=C:excel-sql-server.xlsx', [Sheet1$])
SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:excel-sql-server.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

The Microsoft.Jet.OLEDB.4.0 provider is used with 32-bit SQL Server for Excel 2003 files.

The Microsoft.ACE.OLEDB.12.0 provider is used with 64-bit SQL Server for any Excel files or 32-bit SQL Server for Excel 2007 files.

Pay attention that «Excel 12.0» string is used, not «Excel 14.0» as some MSDN resources say.

Configuration Steps for Excel Data Import to SQL Server

Install Microsoft.ACE.OLEDB.12.0 driver

To import Excel 2007-2016 files to SQL Server Microsoft.ACE.OLEDB.12.0 driver should be installed.

To download the driver use the following link:

Microsoft Access Database Engine 2010 Redistributable

Don’t worry about «Access» in the name.

Warning! x64 driver can not be installed if Microsoft Office 2007-2016 x86 is already installed!

So, there is no way to import Excel data to SQL Server x64 using OPENROWSET/OPENDATASOURCE functions on a machine with Microsoft Office x86!

The SQL Server Error Message if Microsoft.ACE.OLEDB.12.0 is not installed

Msg 7403, Level 16, State 1, Line 1
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" has not been registered.

Configure Ad Hoc Distributed Queries

To configure Ad Hoc Distributed Queries use the following code:

sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

The SQL Server Error Message if Ad Hoc Distributed Queries component is turned off

Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component
'Ad Hoc Distributed Queries' because this component is turned off as part of
the security configuration for this server.
A system administrator can enable the use of 'Ad Hoc Distributed Queries'
by using sp_configure.
For more information about enabling 'Ad Hoc Distributed Queries',
see "Surface Area Configuration" in SQL Server Books Online.

Grant rights to TEMP directory

This step is required only for 32-bit SQL Server with any OLE DB provider.

The main problem is that an OLE DB provider creates a temporary file during the query in the SQL Server temp directory using credentials of a user who run the query.

The default directory for SQL Server is a default directory for SQL Server service account.

If SQL Server is run under Network Service account the temp directory is like:

C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp

If SQL Server is run under Local Service account the temp directory is like:

C:WindowsServiceProfilesLocalServiceAppDataLocalTemp

Microsoft recommends two ways for the solution:

  1. A change of SQL Server TEMP directory and a grant of full rights for all users to this directory.
  2. Grant of read/write rights to the current SQL Server TEMP directory.

See details: PRB: «Unspecified error» Error 7399 Using OPENROWSET Against Jet Database

Usually, only a few accounts are used for import operations. So, we can just add rights for these accounts.

For example, icacls utility can be used for the rights setup:

icacls C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp /grant vs:(R,W)

if SQL Server is started under Network Service and login «vs» is used to run the queries.

The SQL Server Error Message if a user has no rights for SQL Server TEMP directory

OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".

Configure ACE OLE DB properties

This step is required only if the Microsoft.ACE.OLEDB.12.0 provider is used.

Use the following T-SQL code:

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

The SQL Server Error Messages if OLE DB properties are not configured

Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 1
Cannot fetch a row from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

How-To: Import Excel 2003 to SQL Server x86

Step 1. Configure Ad Hoc Distributed Queries

sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

Step 2. Grant rights to TEMP directory

icacls C:WindowsServiceProfiles<SQL Server Account>AppDataLocalTemp /grant <User>:(R,W)

The most commonly used paths:

C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp

C:WindowsServiceProfilesLocalServiceAppDataLocalTemp

Use Microsoft.Jet.OLEDB.4.0 OPENROWSET format

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;Database=C:excel-sql-server.xls', [Sheet1$])

Use Microsoft.Jet.OLEDB.4.0 OPENDATASOURCE format

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
  'Data Source=C:excel-sql-server.xls;Extended Properties=Excel 8.0')...[Sheet1$]

How-To: Import Excel 2007 to SQL Server x86

Step 1. Install the 32-bit Microsoft.ACE.OLEDB.12.0 driver

Microsoft Access Database Engine 2010 Redistributable

Step 2. Configure Ad Hoc Distributed Queries

sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

Step 3. Grant rights to TEMP directory

icacls C:WindowsServiceProfiles<SQL Server Account>AppDataLocalTemp /grant <User>:(R,W)

The most commonly used paths:

C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp

C:WindowsServiceProfilesLocalServiceAppDataLocalTemp

Step 4. Configure OLE DB properties

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

Use Microsoft.ACE.OLEDB.12.0 OPENROWSET format

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
  'Excel 12.0;Database=C:excel-sql-server.xlsx', [Sheet1$])

Use Microsoft.ACE.OLEDB.12.0 OPENDATASOURCE format

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:excel-sql-server.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

How-To: Import Excel 2003/2007 to SQL Server x64

Step 1. Install 64-bit Microsoft.ACE.OLEDB.12.0 driver

Microsoft Access Database Engine 2010 Redistributable

Step 2. Configure Ad Hoc Distributed Queries

sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

Step 3. Configure OLE DB properties

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

Use Microsoft.ACE.OLEDB.12.0 OPENROWSET format

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
  'Excel 12.0;Database=C:excel-sql-server.xlsx', [Sheet1$])

Use Microsoft.ACE.OLEDB.12.0 OPENDATASOURCE format

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:excel-sql-server.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

Conclusion

Using the described techniques you can import data from Microsof Excel 2003-2016 to SQL Server 2005-2016 on the 32-bit or 64-bit platform.

See Also

  • References
  • OPENDATASOURCE (Transact-SQL)
  • OPENROWSET (Transact-SQL)
  • Connection strings for Excel
  • How-To
  • How to use Excel with SQL Server linked servers and distributed queries
  • Accessing Excel files on a x64 machine
  • Downloads
  • Microsoft Access Database Engine 2010 Redistributable
  • Microsoft Access Database Engine 2016 Redistributable

I recently got a new laptop and had to go through the ritual of reinstalling all my programs and drivers. I sometimes work with SSIS locally to import data from Excel and occasionally do demos with Power BI where I read from an Access database so I needed to install the ACE OLE DB provider.  If you try to do either of those things without the ACE OLE DB provider you will get a message like the one below.

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

I needed both the 32-bit and the 64-bit adapters to cover my various use cases. I started by installing the 64-bit Microsoft Access Database Engine 2010 Redistributable.  If you have ever attempted this, you know there is a secret. You cannot install the 2010 Access database engine with a different processing architecture (bittedness) from your Office install (or install both versions of the 2010 Access database engine) without a workaround.  If you try, you will get an error message.

ACE engine bittedness error

There are two options for getting the other version installed.

Option A: Install the 2007 Office System Driver: Data Connectivity Components

The 2007 Access database engine can read the same format, but didn’t have a 64-bit install. It doesn’t have the check to see what other products are on your machine and can co-exist peacefully with the 64-bit 2010 Access engine.

Option B: Install from the Command Line and Use the Passive Switch

  1. Open the command prompt.
  2. Type the file path and file name for your Access Database Engine install file.
  3. Follow it with a space and then “/passive” and then hit Enter.
  4. Delete or rename the mso.dll registry value in the following registry key: HKEY_LOCAL_MACHINESOFTWAREMicrosoftOffice14.0CommonFilesPaths

Note: A helpful commenter has informed me that for Access 2016 the switch is /quiet rather than /passive.

ACE install cmd

I wrote up a document for this a while back for a client, but I can never remember where I put it. So I’m posting this on my blog to make this info easier to find for me as well as you.

  • Remove From My Forums
  • Question

  • We are having a 64Bit compatibility problem.  Something that was working in 32 bit is no longer working in 64 bit.  We need a short / Quick solution for the following:

    The issue we are having is with the

    Microsoft.Jet.OLEDB.4.0 driver. We are using this driver to read and write data to the Excel File (Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=»Excel 8.0;IMEX=1;HDR=YES;»).

    But currently the Microsoft.Jet.OLEDB.4.0 is not supported for the 64 bit OS. The topic titled Deprecated MDAC/WDAC Components in the below given link describes about this issue. It also suggests using a new driver (2007 Office System Driver) as a replacement to the current JET driver. But when I did a quick search about this new driver, it says the 2007 Office System Driver is also currently supported in 32 bit OS versions (need to confirm on this)

Answers

    • Proposed as answer by

      Thursday, March 15, 2012 12:40 PM

    • Marked as answer by
      Ed Price — MSFTMicrosoft employee
      Thursday, August 25, 2016 6:59 AM
    • Marked as answer by
      Michael Sun [MSFT]Microsoft employee
      Monday, January 11, 2010 1:01 AM
  • On more addition tp Lingzhi’s post. I am not sure what exactly you need in terms of functionality, but you could try components for Excel from my web site that are developed in .NET and support both 32- and 64-bit modes.


    Val Mazur (MVP)

    http://www.xporttools.net

    • Marked as answer by
      Michael Sun [MSFT]Microsoft employee
      Monday, January 11, 2010 1:01 AM

    • Marked as answer by
      Michael Sun [MSFT]Microsoft employee
      Monday, January 11, 2010 1:01 AM

  • Posted: 17 Jun 2020
  • Author:
    • Comments: 2
    • Views: 213287
  • ASP.Net
  • Excel
  • Tips
  • OLEDB

Here Mudassar Khan has explained how to download the Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit.

In order to download the Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit, you will need to download the Microsoft Access Database Engine 2010 Redistributable file.

Download FREE API for Word, Excel and PDF in ASP.Net

In this article I will explain how to download the Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit.

In order to download the Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit, you will need to download the Microsoft Access Database Engine 2010 Redistributable file.

Download Microsoft.ACE.OLEDB.12.0 provider

Download the Microsoft Access Database Engine 2010 Redistributable using the following download link.

You need to click the Download button shown in the below screenshot.

Download Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit

Once you click Download it will prompt you to select the architecture i.e. 32 BIT (x86) or 64 BIT (x64).

Download Microsoft.ACE.OLEDB.12.0 provider for 32bit and 64bit

Once downloaded, just right click the Microsoft Access Database Engine 2010 Redistributable file and click install and restart the machine after installation is completed.

Download Free Word/PDF/Excel API

Comments


Comments not available for this article.

Понравилась статья? Поделить с друзьями:
  • Oledb excel connection string
  • Oledb data provider excel
  • Ole таблица excel в autocad
  • Ole работа с word
  • Ole открыть файл excel