Microsoft SQL Server 2005 Standard Edition Microsoft SQL Server 2005 Enterprise Edition Microsoft SQL Server 2005 Developer Edition Microsoft SQL Server 2005 Workgroup Edition More…Less
Summary
Microsoft SQL Server supports connections to other OLE DB data sources on a persistent or an ad hoc basis. The persistent connection is known as a linked server; an ad hoc connection that is made for the sake of a single query is known as a distributed query.
Microsoft Excel workbooks are one type of OLE DB data source that you can query through SQL Server in this manner. This article describes the syntax that is necessary to configure an Excel data source as a linked server, as well as the syntax that is necessary to use a distributed query that queries an Excel data source.
More Information
Querying an Excel data source on a linked server
You can use SQL Server Management Studio or Enterprise Manager, a system stored procedure, SQL-DMO (Distributed Management Objects), or SMO (SQL Server Management Objects) to configure an Excel data source as a SQL Server linked server. (SMO are only available for Microsoft SQL Server 2005.) In all of these cases, you must always set the following four properties:
-
The name that you want to use for the linked server.
-
The OLE DB Provider that is to be used for the connection.
-
The data source or complete path and file name for the Excel workbook.
-
The provider string, which identifies the target as an Excel workbook. By default, the Jet Provider expects an Access database.
The system stored procedure sp_addlinkedserver also expects the @srvproduct property, which can be any string value.
Note If you are using SQL Server 2005, you must specify a value that is not empty for the Product name property in SQL Server Management Studio or for the @srvproduct property in the stored procedure for an Excel data source.
Using SQL Server Management Studio or Enterprise Manager to configure an Excel data source as a linked server
SQL Server Management Studio (SQL Server 2005)
-
In SQL Server Management Studio, expand Server Objects in Object Explorer.
-
Right-click Linked Servers, and then click New linked server.
-
In the left pane, select the General page, and then follow these steps:
-
In the first text box, type any name for the linked server.
-
Select the Other data source option.
-
In the Provider list, click Microsoft Jet 4.0 OLE DB Provider.
-
In the Product name box, type Excel for the name of the OLE DB data source.
-
In the Data source box, type the full path and file name of the Excel file.
-
In the Provider string box, type Excel 8.0 for an Excel 2002, Excel 2000, or Excel 97 workbook.
-
Click OK to create the new linked server.
-
Note In SQL Server Management Studio, you cannot expand the new linked server name to view the list of objects that the server contains.
Enterprise Manager (SQL Server 2000)
-
In Enterprise Manager, click to expand the Security folder.
-
Right-click Linked Servers, and then click New linked server.
-
On the General tab, follow these steps:
-
In the first text box, type any name for the linked server.
-
In the Server type box, click Other data source.
-
In the Provider name list, click Microsoft Jet 4.0 OLE DB Provider.
-
In the Data source box, type the full path and file name of the Excel file.
-
In the Provider string box, type Excel 8.0 for an Excel 2002, Excel 2000, or Excel 97 workbook.
-
Click OK to create the new linked server.
-
-
Click to expand the new linked server name to expand the list of objects that it contains.
-
Under the new linked server name, click Tables. Notice that your worksheets and named ranges appear in the right pane.
Using a stored procedure to configure an Excel data source as a linked server
You can also use the system stored procedure sp_addlinkedserver to configure an Excel data source as a linked server:
DECLARE @RC int
DECLARE @server nvarchar(128)
DECLARE @srvproduct nvarchar(128)
DECLARE @provider nvarchar(128)
DECLARE @datasrc nvarchar(4000)
DECLARE @location nvarchar(4000)
DECLARE @provstr nvarchar(4000)
DECLARE @catalog nvarchar(128)
-- Set parameter values
SET @server = 'XLTEST_SP'
SET @srvproduct = 'Excel'
SET @provider = 'Microsoft.Jet.OLEDB.4.0'
SET @datasrc = 'c:book1.xls'
SET @provstr = 'Excel 8.0'
EXEC @RC = [master].[dbo].[sp_addlinkedserver] @server, @srvproduct, @provider,
@datasrc, @location, @provstr, @catalog
As noted above, this stored procedure requires an additional, arbitrary string value for the @srvproduct argument, which appears as «Product name» in the Enterprise Manager and SQL Server Management Studio configuration. The @location and @catalog arguments are not used.
Using SQL-DMO to configure an Excel data source as a linked server
You can use SQL Distributed Management Objects to configure an Excel data source as a linked server programmatically from Microsoft Visual Basic or another programming language. You must supply the same four arguments that are required in the Enterprise Manager and SQL Server Management Studio configuration.
Private Sub Command1_Click()
Dim s As SQLDMO.SQLServer
Dim ls As SQLDMO.LinkedServer
Set s = New SQLDMO.SQLServer
s.Connect "(local)", "sa", "password"
Set ls = New SQLDMO.LinkedServer
With ls
.Name = "XLTEST_DMO"
.ProviderName = "Microsoft.Jet.OLEDB.4.0"
.DataSource = "c:book1.xls"
.ProviderString = "Excel 8.0"
End With
s.LinkedServers.Add ls
s.Close
End Sub
Using SMO to configure an Excel data source as a linked server
In SQL Server 2005, you can use SQL Server Management Objects (SMO) to configure an Excel data source as a linked server programmatically. To do this, you can use Microsoft Visual Basic .NET or another programming language. You must supply the arguments that are required in the SQL Server Management Studio configuration. The SMO object model extends and supersedes the Distributed Management Objects (SQL-DMO) object model. Because SMO is compatible with SQL Server version 7.0, SQL Server 2000, and SQL Server 2005, you can also use SMO for configuration of SQL Server 2000.
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.CommonPublic Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As Server
Dim conn As ServerConnection
Dim ls As LinkedServerconn = New ServerConnection("ServerNameInstanceName", "YourUesrName", "YourPassword")
s = New Server(conn)
Try
ls = New LinkedServer(s, "XLTEST_DMO")
With ls
.ProviderName = "Microsoft.Jet.OLEDB.4.0"
.ProductName = "Excel"
.DataSource = "c:book1.xls"
.ProviderString = "Excel 8.0"
End With
ls.Create()
MessageBox.Show("New linked Server has been created.")
Catch ex As SmoException
MessageBox.Show(ex.Message)
Finally
ls = Nothing
If s.ConnectionContext.IsOpen = True Then
s.ConnectionContext.Disconnect()
End If
End TryEnd Sub
End Class
Querying an Excel data source on a linked server
After you configure an Excel data source as a linked server, you can easily query its data from Query Analyzer or another client application. For example, to retrieve the rows of data that are stored in Sheet1 of your Excel file, the following code uses the linked server that you configured by using SQL-DMO:
SELECT * FROM XLTEST_DMO...Sheet1$
You can also use OPENQUERY to query the Excel linked server in a «passthrough» manner, as follows:
SELECT * FROM OPENQUERY(XLTEST_DMO, 'SELECT * FROM [Sheet1$]')
The first argument that OPENQUERY expects is the linked server name. Delimiters are required for worksheet names, as shown above.
You can also obtain a list of all the tables that are available on the Excel linked server by using the following query:
EXECUTE SP_TABLES_EX 'XLTEST_DMO'
Querying an Excel data source by using distributed queries
You can use SQL Server distributed queries and the OPENDATASOURCE or OPENROWSET function to query infrequently accessed Excel data sources on an ad hoc basis.
Note If you are using SQL Server 2005, make sure that you have enabled the Ad Hoc Distributed Queries option by using SQL Server Surface Area Configuration, as in the following example:
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=c:book1.xls;Extended Properties=Excel 8.0')...Sheet1$
Note that OPENROWSET uses an uncommon syntax for the second («Provider String») argument:
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:book1.xls', Sheet1$)
The syntax that an ActiveX Data Objects (ADO) developer may expect to use for the second («Provider String») argument with OPENROWSET:
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Data Source=c:book1.xls;Extended Properties=Excel 8.0', Sheet1$)
This syntax raises the following error from the Jet Provider:
Could not find installable ISAM.
Note This error also occurs if you enter DataSource instead of Data Source. For example, the following argument is incorrect:
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'DataSource=c:book1.xls;Extended Properties=Excel 8.0', Sheet1$)
References
Because SQL Server linked servers and distributed queries use the OLE DB Provider, the general guidelines and cautions about using ADO with Excel apply here.
For more information, click the following article number to view the article in the Microsoft Knowledge Base:
257819 How to use ADO with Excel data from Visual Basic or VBA
For more information about SQL Server Management Objects, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/library/ms162169(ide).aspxFor more information about how to enable the Ad Hoc Distributed Queries option, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/ms189978(ide).aspx
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
Introduction
This article describes the complete steps for Microsoft Excel data import to SQL Server using linked servers 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 using linked servers
- Configuration steps for Excel data import to SQL Server using linked servers
- Install Microsoft.ACE.OLEDB.12.0 driver
- Grant rights to TEMP directory
- Configure ACE OLE DB properties
- Configure linked servers
- 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 Using Linked Servers
To import data from Microsoft Excel 2003 files to 32-bit SQL Server the Microsoft.Jet.OLEDB.4.0 provider can be used. Use the T-SQL code like this to add a linked server to Excel 2003 workbook:
EXEC sp_addlinkedserver @server = 'ExcelServer1', @srvproduct = 'Excel', @provider = 'Microsoft.Jet.OLEDB.4.0', @datasrc = 'C:Testexcel-sql-server.xls', @provstr = 'Excel 8.0;IMEX=1;HDR=YES;'
To import data from Microsoft Excel 2007 to 32-bit SQL Server or from any Microsoft Excel files to 64-bit SQL Server the Microsoft.ACE.OLEDB.12.0 provider should be used. Use the T-SQL code like this:
EXEC sp_addlinkedserver @server = 'ExcelServer2', @srvproduct = 'Excel', @provider = 'Microsoft.ACE.OLEDB.12.0', @datasrc = 'C:Testexcel-sql-server.xlsx', @provstr = 'Excel 12.0;IMEX=1;HDR=YES;'
IMEX=1 defines to import all Excel column data including data of mixed types.
HDR=YES defines that Excel data contain column headers.
The way to modify a linked server is to drop and create it again. Use the T-SQL code like this:
EXEC sp_dropserver @server = N'ExcelServer1', @droplogins='droplogins'
There are two ways to use linked server data. The first way is like this:
SELECT * FROM ExcelServer1...[Sheet1$]
and the second one is the use of the OPENQUERY function:
SELECT * FROM OPENQUERY(ExcelServer1, 'SELECT * FROM [Sheet1$]')
The use of the OPENQUERY function is more flexible because queries can contain Excel ranges unlike the entire sheet in the first case.
Configuration Steps for Excel Data Import to SQL Server Using Linked Servers
Install Microsoft.ACE.OLEDB.12.0 driver
To import Excel 2007-2016 files to SQL Server the 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 cannot 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 Linked Servers technique on a machine with Microsoft Office x86!
The SQL Server Error Message if Microsoft.ACE.OLEDB.12.0 is not installed
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "ExcelServer2" returned message "The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.". Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "ExcelServer2".
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 the Network Service account the temp directory is like:
C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp
If SQL Server is run under the Local Service account the temp directory is like:
C:WindowsServiceProfilesLocalServiceAppDataLocalTemp
Microsoft recommends two ways for the solution:
- A change of SQL Server TEMP directory and a grant of full rights for all users to this directory.
- 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 the 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 "ExcelServer1" 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 "ExcelServer1".
or the message for Microsoft.ACE.OLEDB.12.0 provider:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "ExcelServer2" returned message "Unspecified error". Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "ExcelServer2".
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 "ExcelServer2" 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 "ExcelServer2".
Configure linked servers
The configuring of linked servers is discussed in the Basics topic.
Use the T-SQL code like this for Excel 2003 linked servers:
EXEC sp_addlinkedserver @server = 'ExcelServer1', @srvproduct = 'Excel', @provider = 'Microsoft.Jet.OLEDB.4.0', @datasrc = 'C:Testexcel-sql-server.xls', @provstr = 'Excel 8.0;IMEX=1;HDR=YES;'
Use the T-SQL code like this for Excel 2007 linked servers or on SQL Server x64:
EXEC sp_addlinkedserver @server = 'ExcelServer2', @srvproduct = 'Excel', @provider = 'Microsoft.ACE.OLEDB.12.0', @datasrc = 'C:Testexcel-sql-server.xlsx', @provstr = 'Excel 12.0;IMEX=1;HDR=YES;'
How-To: Import Excel 2003 to SQL Server x86
Step 1. 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 2. Configure linked server using Microsoft.Jet.OLEDB.4.0 provider
EXEC sp_addlinkedserver @server = 'ExcelServer1', @srvproduct = 'Excel', @provider = 'Microsoft.Jet.OLEDB.4.0', @datasrc = 'C:Testexcel-sql-server.xls', @provstr = 'Excel 8.0;IMEX=1;HDR=YES;'
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. 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 3. Configure ACE 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
Step 4. Configure linked server using Microsoft.ACE.OLEDB.12.0 provider
EXEC sp_addlinkedserver @server = 'ExcelServer2', @srvproduct = 'Excel', @provider = 'Microsoft.ACE.OLEDB.12.0', @datasrc = 'C:Testexcel-sql-server.xlsx', @provstr = 'Excel 12.0;IMEX=1;HDR=YES;'
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 ACE 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
Step 3. Configure linked server using Microsoft.ACE.OLEDB.12.0 provider
EXEC sp_addlinkedserver @server = 'ExcelServer2', @srvproduct = 'Excel', @provider = 'Microsoft.ACE.OLEDB.12.0', @datasrc = 'C:Testexcel-sql-server.xlsx', @provstr = 'Excel 12.0;IMEX=1;HDR=YES;'
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
- OPENQUERY (Transact-SQL)
- How-To
- How to use Excel with SQL Server linked servers and distributed queries
- Downloads
- Microsoft Access Database Engine 2010 Redistributable
- Microsoft Access Database Engine 2016 Redistributable
title | description | author | ms.author | ms.date | ms.service | ms.subservice | ms.topic | monikerRange |
---|---|---|---|---|---|---|---|---|
Import data from Excel to SQL Server or Azure SQL Database |
This article describes methods to import data from Excel to SQL Server or Azure SQL Database. Some use a single step, others require an intermediate text file. |
rwestMSFT |
randolphwest |
03/30/2023 |
sql |
data-movement |
conceptual |
=azuresqldb-current||>=sql-server-2016||>=sql-server-linux-2017||=azuresqldb-mi-current |
Import data from Excel to SQL Server or Azure SQL Database
[!INCLUDE SQL Server Azure SQL Database]
There are several ways to import data from Excel files to [!INCLUDE ssnoversion-md] or to Azure SQL Database. Some methods let you import data in a single step directly from Excel files; other methods require you to export your Excel data as text (CSV file) before you can import it.
This article summarizes the frequently used methods and provides links for more detailed information. A complete description of complex tools and services like SSIS or Azure Data Factory is beyond the scope of this article. To learn more about the solution that interests you, follow the provided links.
List of methods
There are several ways to import data from Excel. You may need to install SQL Server Management Studio (SSMS) to use some of these tools.
You can use the following tools to import data from Excel:
Export to text first ([!INCLUDE ssnoversion-md] and SQL Database) | Directly from Excel ([!INCLUDE ssnoversion-md] on-premises only) |
---|---|
Import Flat File Wizard | SQL Server Import and Export Wizard |
BULK INSERT statement | SQL Server Integration Services (SSIS) |
BCP | OPENROWSET function |
Copy Wizard (Azure Data Factory) | |
Azure Data Factory |
If you want to import multiple worksheets from an Excel workbook, you typically have to run any of these tools once for each sheet.
[!IMPORTANT]
To learn more, see limitations and known issues for loading data to or from Excel files.
Import and Export Wizard
Import data directly from Excel files by using the [!INCLUDE ssnoversion-md] Import and Export Wizard. You also can save the settings as a SQL Server Integration Services (SSIS) package that you can customize and reuse later.
-
In [!INCLUDEssManStudioFull], connect to an instance of the [!INCLUDEssNoVersion] [!INCLUDEssDE].
-
Expand Databases.
-
Right-click a database.
-
Select Tasks.
-
Choose to Import Data or Export Data:
:::image type=»content» source=»../../integration-services/import-export-data/media/start-wizard-ssms.jpg» alt-text=»Start wizard SSMS»:::
This launches the wizard:
:::image type=»content» source=»media/excel-connection.png» alt-text=»Connect to an Excel data source»:::
To learn more, review:
- Start the SQL Server Import and Export Wizard
- Get started with this simple example of the Import and Export Wizard
Integration Services (SSIS)
If you’re familiar with SQL Server Integration Services (SSIS) and don’t want to run the [!INCLUDE ssnoversion-md] Import and Export Wizard, create an SSIS package that uses the Excel Source and the [!INCLUDE ssnoversion-md] Destination in the data flow.
To learn more, review:
- Excel Source
- SQL Server Destination
To start learning how to build SSIS packages, see the tutorial How to Create an ETL Package.
:::image type=»content» source=»media/excel-to-sql-data-flow.png» alt-text=»Components in the data flow»:::
OPENROWSET and linked servers
[!IMPORTANT]
In Azure SQL Database, you cannot import directly from Excel. You must first export the data to a text (CSV) file.
[!NOTE]
The ACE provider (formerly the Jet provider) that connects to Excel data sources is intended for interactive client-side use. If you use the ACE provider on [!INCLUDE ssnoversion-md], especially in automated processes or processes running in parallel, you may see unexpected results.
Distributed queries
Import data directly into [!INCLUDE ssnoversion-md] from Excel files by using the Transact-SQL OPENROWSET
or OPENDATASOURCE
function. This usage is called a distributed query.
[!IMPORTANT]
In Azure SQL Database, you cannot import directly from Excel. You must first export the data to a text (CSV) file.
Before you can run a distributed query, you have to enable the ad hoc distributed queries
server configuration option, as shown in the following example. For more info, see ad hoc distributed queries Server Configuration Option.
sp_configure 'show advanced options', 1; RECONFIGURE; GO sp_configure 'ad hoc distributed queries', 1; RECONFIGURE; GO
The following code sample uses OPENROWSET
to import the data from the Excel Sheet1
worksheet into a new database table.
USE ImportFromExcel; GO SELECT * INTO Data_dq FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0; Database=C:TempData.xlsx', [Sheet1$]); GO
Here’s the same example with OPENDATASOURCE
.
USE ImportFromExcel; GO SELECT * INTO Data_dq FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0', 'Data Source=C:TempData.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]; GO
To append the imported data to an existing table instead of creating a new table, use the INSERT INTO ... SELECT ... FROM ...
syntax instead of the SELECT ... INTO ... FROM ...
syntax used in the preceding examples.
To query the Excel data without importing it, just use the standard SELECT ... FROM ...
syntax.
For more info about distributed queries, see the following articles:
- Distributed Queries (Distributed queries are still supported in [!INCLUDE sssql19-md], but the documentation for this feature hasn’t been updated.)
- OPENROWSET
- OPENDATASOURCE
Linked servers
You can also configure a persistent connection from [!INCLUDE ssnoversion-md] to the Excel file as a linked server. The following example imports the data from the Data
worksheet on the existing Excel linked server EXCELLINK
into a new [!INCLUDE ssnoversion-md] database table named Data_ls
.
USE ImportFromExcel; GO SELECT * INTO Data_ls FROM EXCELLINK...[Data$]; GO
You can create a linked server from SQL Server Management Studio (SSMS), or by running the system stored procedure sp_addlinkedserver
, as shown in the following example.
DECLARE @RC INT; DECLARE @server NVARCHAR(128); DECLARE @srvproduct NVARCHAR(128); DECLARE @provider NVARCHAR(128); DECLARE @datasrc NVARCHAR(4000); DECLARE @location NVARCHAR(4000); DECLARE @provstr NVARCHAR(4000); DECLARE @catalog NVARCHAR(128); -- Set parameter values SET @server = 'EXCELLINK'; SET @srvproduct = 'Excel'; SET @provider = 'Microsoft.ACE.OLEDB.12.0'; SET @datasrc = 'C:TempData.xlsx'; SET @provstr = 'Excel 12.0'; EXEC @RC = [master].[dbo].[sp_addlinkedserver] @server, @srvproduct, @provider, @datasrc, @location, @provstr, @catalog;
For more info about linked servers, see the following articles:
- Create Linked Servers
- OPENQUERY
For more examples and info about both linked servers and distributed queries, see the following article:
- How to use Excel with SQL Server linked servers and distributed queries
Prerequisite — Save Excel data as text
To use the rest of the methods described on this page — the BULK INSERT statement, the BCP tool, or Azure Data Factory — first you have to export your Excel data to a text file.
In Excel, select File | Save As and then select Text (Tab-delimited) (*.txt) or CSV (Comma-delimited) (*.csv) as the destination file type.
If you want to export multiple worksheets from the workbook, select each sheet, and then repeat this procedure. The Save as command exports only the active sheet.
[!TIP]
For best results with data importing tools, save sheets that contain only the column headers and the rows of data. If the saved data contains page titles, blank lines, notes, and so forth, you may see unexpected results later when you import the data.
The Import Flat File Wizard
Import data saved as text files by stepping through the pages of the Import Flat File Wizard.
As described previously in the Prerequisite section, you have to export your Excel data as text before you can use the Import Flat File Wizard to import it.
For more info about the Import Flat File Wizard, see Import Flat File to SQL Wizard.
BULK INSERT command
BULK INSERT
is a Transact-SQL command that you can run from SQL Server Management Studio. The following example loads the data from the Data.csv
comma-delimited file into an existing database table.
As described previously in the Prerequisite section, you have to export your Excel data as text before you can use BULK INSERT to import it. BULK INSERT can’t read Excel files directly. With the BULK INSERT command, you can import a CSV file that is stored locally or in Azure Blob storage.
USE ImportFromExcel; GO BULK INSERT Data_bi FROM 'C:Tempdata.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = 'n' ); GO
For more info and examples for [!INCLUDE ssnoversion-md] and SQL Database, see the following articles:
- Import Bulk Data by Using BULK INSERT or OPENROWSET(BULK…)
- BULK INSERT
BCP tool
BCP is a program that you run from the command prompt. The following example loads the data from the Data.csv
comma-delimited file into the existing Data_bcp
database table.
As described previously in the Prerequisite section, you have to export your Excel data as text before you can use BCP to import it. BCP can’t read Excel files directly. Use to import into [!INCLUDE ssnoversion-md] or SQL Database from a test (CSV) file saved to local storage.
[!IMPORTANT]
For a text (CSV) file stored in Azure Blob storage, use BULK INSERT or OPENROWSET. For an examples, see Example.
bcp.exe ImportFromExcel..Data_bcp in "C:Tempdata.csv" -T -c -t ,
For more info about BCP, see the following articles:
- Import and Export Bulk Data by Using the bcp Utility
- bcp Utility
- Prepare Data for Bulk Export or Import
Copy Wizard (ADF)
Import data saved as text files by stepping through the pages of the Azure Data Factory (ADF) Copy Wizard.
As described previously in the Prerequisite section, you have to export your Excel data as text before you can use Azure Data Factory to import it. Data Factory can’t read Excel files directly.
For more info about the Copy Wizard, see the following articles:
- Data Factory Copy Wizard
- Tutorial: Create a pipeline with Copy Activity using Data Factory Copy Wizard.
Azure Data Factory
If you’re familiar with Azure Data Factory and don’t want to run the Copy Wizard, create a pipeline with a Copy activity that copies from the text file to [!INCLUDE ssnoversion-md] or to Azure SQL Database.
As described previously in the Prerequisite section, you have to export your Excel data as text before you can use Azure Data Factory to import it. Data Factory can’t read Excel files directly.
For more info about using these Data Factory sources and sinks, see the following articles:
- File system
- SQL Server
- Azure SQL Database
To start learning how to copy data with Azure data factory, see the following articles:
- Move data by using Copy Activity
- Tutorial: Create a pipeline with Copy Activity using Azure portal
Common errors
Microsoft.ACE.OLEDB.12.0″ hasn’t been registered
This error occurs because the OLEDB provider isn’t installed. Install it from Microsoft Access Database Engine 2010 Redistributable. Be sure to install the 64-bit version if Windows and [!INCLUDE ssnoversion-md] are both 64-bit.
The full error is:
Msg 7403, Level 16, State 1, Line 3
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" has not been registered.
Cannot create an instance of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»
This indicates that the Microsoft OLEDB hasn’t been configured properly. Run the following Transact-SQL code to resolve this:
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1; EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1;
The full error is:
Msg 7302, Level 16, State 1, Line 3
Cannot create an instance of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
The 32-bit OLE DB provider «Microsoft.ACE.OLEDB.12.0» cannot be loaded in-process on a 64-bit SQL Server
This occurs when a 32-bit version of the OLD DB provider is installed with a 64-bit [!INCLUDE ssnoversion-md]. To resolve this issue, uninstall the 32-bit version and install the 64-bit version of the OLE DB provider instead.
The full error is:
Msg 7438, Level 16, State 1, Line 3
The 32-bit OLE DB provider "Microsoft.ACE.OLEDB.12.0" cannot be loaded in-process on a 64-bit SQL Server.
The OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)» reported an error.
Cannot initialize the data source object of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»
Both of these errors typically indicate a permissions issue between the [!INCLUDE ssnoversion-md] process and the file. Ensure that the account that is running the [!INCLUDE ssnoversion-md] service has full access permission to the file. We recommend against trying to import files from the desktop.
The full errors are:
Msg 7399, Level 16, State 1, Line 3
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 7303, Level 16, State 1, Line 3
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
Next steps
- Get started with this simple example of the Import and Export Wizard
- Import data from Excel or export data to Excel with SQL Server Integration Services (SSIS)
- bcp Utility
- Move data by using Copy Activity
For those who are using SQL SERVER 2012+ you can use the Microsoft OLEDB 12.0 Provider that comes with SQL Server 2012+ and which allows you to use Excel 2007-2013 xlsx files for adhoc distributed queries or as a linked server. Examples below.
The Excel workbook ‘Application.xlsx’ has 3 worksheets Application,Device,User
First Activate Ad Hoc Queries on the Server.
USE MSDB
GO
sp_configure 'show advanced options', 1
GO
RECONFIGURE WITH OverRide
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE WITH OverRide
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
For Ad Hoc Queries use the OPENROWSET Function.
SELECT * FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:UsersAdministratorDesktopApplication.xlsx;HDR=YES', 'SELECT * FROM [Application$]');
SELECT * FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:UsersAdministratorDesktopApplication.xlsx;HDR=YES', 'SELECT * FROM [Device$]');
SELECT * FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:UsersAdministratorDesktopApplication.xlsx;HDR=YES', 'SELECT * FROM [User$]');
For Creating a Linked Server for Excel 2007-2013 format:
USE MSDB
GO
EXEC sp_addLinkedServer
@server= 'XLSX_MATRIX',
@srvproduct = 'ACE 12.0',
@provider = 'Microsoft.ACE.OLEDB.12.0',
@datasrc = 'C:UsersAdministratorDesktopApplication.xlsx',
@provstr = 'Excel 12.0; HDR=Yes'
Now, query your excel file in two ways:
SELECT * FROM OPENQUERY (XLSX_MATRIX, 'Select * from [Application$]')
SELECT * FROM OPENQUERY (XLSX_MATRIX, 'Select * from [Device$]')
SELECT * FROM OPENQUERY (XLSX_MATRIX, 'Select * from [User$]')
SELECT * FROM XLSX_MATRIX...[Application$]
SELECT * FROM XLSX_MATRIX...[Device$]
SELECT * FROM XLSX_MATRIX...[User$]
Table of Contents
- Introduction
- Building the Environment for Testing
- Creating an Excel File to test
- Installing the necessary components in Windows Server
- Enabling SQL Server Instance to Read File
- Querying and Importing the Spreadsheet
- Conclusion
- References
- See Also
- Other Languages
Introduction
We often have to perform data integration in SQL Server, with different data sources such as «.txt» files (tabular text or with separator character), «.csv» files or «.xls» (Excel) files.
It is always not possible to create a SSIS package to do this data import, a useful alternative is to use OPENROWSET method for importing data.
In this article, we will use data import from Excel files (.xls e .xlsx).
Building the Environment for Testing
So that we see the data import process steps from an Excel file to a table from database, we need:
- Create an Excel file to import sample;
- Configure Windows Server, installing the necessary components;
- Configure the necessary permissions to the SQL instance that we need to obtain data files.
Let’s prepare environment for data import!
Creating an Excel File to test
In this step, we will create an Excel file sample with just a few rows to demo.
Add a header row, to explicitly define the data: «ID», «Item Name» and «Date Created».
The data sequences is only to facilitate the visualization of the content that is being manipulated.
See this Excel file in the image below (click to enlarge)
Installing the necessary components in Windows Server
To get the data through a query inside SQL Server, use an OLE DB Data Provider.
Most files can now use the
Microsoft.ACE.OLEDB.12.0 Data Provider that can be obtained free through Data Connectivity Components.
This package will provide all ODBC and OLEDB drivers for data manipulation, as follow below:
File Type (extension) | Extended Properties |
Excel 97-2003 Workbook (.xls) | Excel 8.0 |
Excel 2007-2010 Workbook (.xlsx) | Excel 12.0 XML |
Excel 2007-2010 Macro-enabled workbook (.xlsm) | Excel 12.0 Macro |
Excel 2007-2010 Non-XML binary workbook (.xlsb) | Excel 12.0 |
There are two versions of this package: «AccessDatabaseEngine.exe» for x86 platform and other «AccessDatabaseEngine_x64.exe» for x64 platform.
The minimum system requirements for this installation can be obtained in the same
download package page.
If you are installing the x86 package you must ensure that your user is allowed access to the Temporary directory of your Windows OS.
To know what your Temporary directory open the «Control Panel», click «Advanced System Settings» option. A window will open, select the «Advanced» tab and click the «Environment Variables» button.
A new window will open with your environment variables, including «TEMP» and «TMP» variables, indicating your Temporary directory.
See this windows in the image below (click to enlarge)
So if your operating system is Windows 32-bit (x86) is necessary to include read and write access to the user of your SQL Server instance.
It’s important to remember that the user of your SQL Server instance must be a local user or the default «Local System» account to grant this access.
See this window Service Properties in the image below
Enabling SQL Server Instance to Read File
The settings and permissions to execute a query external data has some details that should be performed to be able to get the data from an Excel files (.xls ou .xlsx) and also other formats.
The execution of distributed queries as OPENROWSET is only possible when the SQL Server instance has the
Ad Hoc Distributed Queries configuration enabled. By default, every SQL Server instance maintains this permission denied.
Note |
---|
The Advanced Settings should only be changed by an experienced professional or a certified professional in SQL Server. It’s important to note not use these commands in Production Databases without previous analysis. |
To enable this feature just use the sp_configure system stored procedure in your SQL instance to display its Advanced Settings in
show advanced options parameter and soon to follow, enable the Ad Hoc Distributed Queries setting to enabling the use of distributed queries.
USE [master]
GO
—CONFIGURING SQL INSTANCE TO ACCEPT ADVANCED OPTIONS
EXEC
sp_configure ‘show advanced options’, 1
RECONFIGURE
GO
—ENABLING USE OF DISTRIBUTED QUERIES
EXEC
sp_configure ‘Ad Hoc Distributed Queries’, 1
RECONFIGURE
GO
These changes in the Advanced settings only take effect after the execution of the RECONFIGURE command.
To get permission granted to use the Data Provider through sp_MSset_oledb_prop system stored procedure to link Microsoft.ACE.OLEDB.12.0 in
SQL Server using AllowInProcess parameter so we can use the resources of the Data Provider and also allow the use of dynamic parameters in queries through of
DynamicParameters parameter for our queries can use T-SQL clauses.
USE [master]
GO
—ADD DRIVERS IN SQL INSTANCE
EXEC
master.dbo.sp_MSset_oledb_prop
N’Microsoft.ACE.OLEDB.12.0′,
N’AllowInProcess’, 1
GO
EXEC
master.dbo.sp_MSset_oledb_prop
N’Microsoft.ACE.OLEDB.12.0′,
N’DynamicParameters’, 1
GO
See
this output SQL script in the image below
After setting up your SQL instance to use the
Microsoft.ACE.OLEDB.12.0 Data Provider and make the appropriate access permissions, we can implement the distributed queries of other data sources,
in this case to Excel files.
Querying and Importing the Spreadsheet
As this demo is for Excel files (.xls) we will perform a query using an OPENROWSET method with the Excel test file that was created earlier in this article.
We use some parameters for this method to be able to data query:
- Data Provider — In this case, using Microsoft.ACE.OLEDB.12.0
- BULK Options — File Version;Where it’s stored; Header (HDR); Import Mode (IMEX)
- Query —
T-SQL statement with or without clauses to data filter and process.
—CONSULTING A SPREADSHEET
SELECT
* FROM
OPENROWSET(‘Microsoft.ACE.OLEDB.12.0’,
‘Excel 12.0; Database=C:MicrosoftTest.xls; HDR=YES; IMEX=1’,
‘SELECT * FROM [Plan1$]’)
GO
See
this output SQL script in the image below
To data group and perform other tasks for data manipulation, the ideal is always load the data into the database. You can insert data into an existing table using the INSERT statement or you can create a table through of INTO command in SELECT statement.
—CONSULTING A SPREADSHEET
SELECT *
INTO
TB_EXAMPLE
FROM OPENROWSET(‘Microsoft.ACE.OLEDB.12.0’,
‘Excel 12.0; Database=C:MicrosoftTest.xls; HDR=YES; IMEX=1’,
‘SELECT * FROM [Plan1$]’)
GO
SELECT * FROM TB_EXAMPLE
GO
See
this output SQL script in the image below
It’s also important to check if the SQL Server Service user has access in Windows directory where Excel files
are stored.
Conclusion
Have the possibility to use an alternative resource for importing data with T-SQL command is very useful, especially when we have to manipulate files in proprietary formats, as for .xlsx files where it’s necessary to use the Data Provider appropriate to obtain
the data correctly and with ease use.
It’s important to watch out that only users that have actually need to manipulate these files can use these resources, while minimizing the vulnerability of their environment through a permission in your SQL Server.
References
- OPENROWSET (Transact-SQL)
- Import Bulk Data by Using BULK INSERT or OPENROWSET(BULK…) (SQL Server)
- OLE DB Providers Tested with SQL Server
- Excel Source
See Also
- Transact-SQL Portal
- Wiki: Portal of TechNet Wiki Portals
Other Languages
- Importando uma planilha Excel para um Banco de Dados SQL Server (pt-BR)
This article was awarded the silver medal in the TechNet
Guru of April 2014