Link excel and sql server

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)
  1. In SQL Server Management Studio, expand Server Objects in Object Explorer.

  2. Right-click Linked Servers, and then click New linked server.

  3. In the left pane, select the General page, and then follow these steps:

    1. In the first text box, type any name for the linked server.

    2. Select the Other data source option.

    3. In the Provider list, click Microsoft Jet 4.0 OLE DB Provider.

    4. In the Product name box, type Excel for the name of the OLE DB data source.

    5. In the Data source box, type the full path and file name of the Excel file.

    6. In the Provider string box, type Excel 8.0 for an Excel 2002, Excel 2000, or Excel 97 workbook.

    7. 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)
  1. In Enterprise Manager, click to expand the Security folder.

  2. Right-click Linked Servers, and then click New linked server.

  3. On the General tab, follow these steps:

    1. In the first text box, type any name for the linked server.

    2. In the Server type box, click Other data source.

    3. In the Provider name list, click Microsoft Jet 4.0 OLE DB Provider.

    4. In the Data source box, type the full path and file name of the Excel file.

    5. In the Provider string box, type Excel 8.0 for an Excel 2002, Excel 2000, or Excel 97 workbook.

    6. Click OK to create the new linked server.

  4. Click to expand the new linked server name to expand the list of objects that it contains.

  5. 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.Common

Public 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 LinkedServer

conn = 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 Try

End 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:

  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 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

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$]

In a previous article, we spoke about why you need both Excel and SQL in your data management solutions, but how do you connect Excel to SQL Server?  In this article, we’re going to show you the steps and highlight a key benefit of using an Excel add-in like SQL Spreads.

But, first, we’re going to re-cap the benefits of connecting Excel to data in SQL Server.

Table of contents

  • 1. Benefits of connecting Excel to SQL Server
  • 2. Connect Excel to a SQL Server database : 3 easy steps
    • a. Step 1: Gather the database connection details
    • b. Step 2: Connect to SQL Server
    • c. Step 3: Select the relevant table in SQL Server
  • 3. Example: A simple Quote form in Excel connected to SQL Server
    • a. Connection details
    • b. Connect to SQL Server
    • c. Select the Production.Product table in SQL Server
    • d. Bonus Feature!  Update prices in Excel and save to SQL Server
  • 4. Summary

Benefits of connecting Excel to SQL Server

To demonstrate the benefits of connecting Excel to SQL Server, let’s look at an example.

This spreadsheet is used by Sales Reps at a manufacturing company to prepare quotes for customers.  Each Sales Rep has a copy of the spreadsheet, which includes a list of inventory items and their prices.  The list of inventory items and prices is extracted from the finance system by an administrator.  The quote sheet uses some data validation lookup formulas to retrieve the prices when a Sales Rep selects an item from the dropdown.

Quote Example quote sheet

This works well until the organization needs to update the prices. In which case, each user would need to copy and paste the new pricing into the spreadsheet (or use a new copy of the spreadsheet).  Also, when the Sales Rep creates the quote, they don’t know whether the items are actually in stock.

A better solution would be to connect the Excel spreadsheet to the inventory table in the finance system database.  Each time the Sales Rep opens the quote spreadsheet, they are refreshing the price data from the live database.  We can go one step further and make the connection to the database also bring back the current stock levels so that quotes can be prepared for items actually in stock.

So, to summarise, the benefits of connecting Excel to SQL Server are:

  • we have access and can view up-to-date information
  • we are using one single, trusted data source
  • we can perform on-the-fly analysis or aggregation of the source data using simple Excel functions like pivot tables

Connect Excel to a SQL Server database : 3 easy steps

The easiest way to connect Excel to a SQL Server database is with SQL Spreads.  SQL Spreads is a simple Excel add-in.

The SQL Spreads download can be found here, and the installation process is described here.

Step 1: Gather the database connection details

You’ll need the following information to connect Excel to SQL Server, so get the details as the first step:

  • SQL Server Name
  • Database Name
  • Table or View that contains the information you need
  • Login details (if not using Windows authentication)

The form of the SQL Server Name will depend on whether SQL Server is installed locally, on a network, or a remote location (note that this is the same name as when you connect to SQL Server in SQL Server Management Studio).

Typical server name Case
Localhost When SQL Server is installed locally
localhostsqlexpress When SQL Server Express is installed locally
DomainServername When SQL Server is installed in a corporate network
IP-address When SQL Server is installed in a remote location

Step 2: Connect to SQL Server

Once SQL Spreads is installed, you’ll see it as a new ribbon tab; go here and click the Design Mode button.

Open the SQL Spreads Designer in Excel

In the SQL Spreads Designer panel on the right side, click the Edit button to open the SQL Server connection dialog.

Open the SQL Server connection dialog

Enter the name of your SQL Server into the SQL Server name field:

Connect to SQL Server dialog

Select if you should connect using your Windows login (Windows Authentication) or enter a user name and password (SQL Server Authentication).  Windows authentication is the more secure of the two options (see here for more information).

Select SQL Server authentication method

Click OK. SQL Spreads will try to connect to the database. If the connection is successful, your databases will show up in the SQL Spreads Designer panel.

SQL Spreads Designer database list

Step 3: Select the relevant table in SQL Server

Now that we’ve created the connection from Excel to SQL Server, we can select which table of data we want to use in Excel.

In the SQL Spreads Designer, click on the database and then select your table.

SQL Spreads Designer AW Table list

As soon as you select a table, the data in the table is populated in the Excel sheet.

You can now see all the data in your SQL Server table and use it in your Excel workbook.  The real power with SQL Spreads is the ability to update the data in the table in SQL Server direct from Excel.  For example, I can update the prices in the product table directly in Excel, and save the changes back to SQL Server!

Quote example Save to Database

Example: A simple Quote form in Excel connected to SQL Server

Let’s go back to our earlier example of the quote form and the inventory list.  We’re going to change this so that the quote form gets its data from the table in the SQL server instead of a static list in the spreadsheet.

If you want to follow along with this example, you’ll need to have access to the AdventureWorks sample database, which you can get from here.   

First, we’re going to create a new sheet in the quote_sample workbook and leave it with the default name of Sheet2 – the data from SQL Server will be populated here.

Quote example add new sheet

Next, we’re going to connect to the AdventureWorks database using the steps outlined above.

Step (1) : Connection details

Here are the connection details I’m going to use to connect to my SQL Server database:

  • SQL Server Name: AndySQLExpress
  • Database Name: AdventureWorks
  • Table or View: Production.Product
  • Login details: Windows authentication

Step (2): Connect to SQL Server

We want to connect to the Product table in SQL Server and populate the ‘Product’ sheet in the quote worksheet. To do this we click on SQL Spreads > Design Mode and enter the connection details and expand the correct database (in our case, AdventureWorks) so that we can select the relevant table (in our case, Production.Product).

Quote example connection details

Step (3): Select the Production.Product table in SQL Server

Click on the Production.Product table in the list and the data is automatically populated into the Product sheet.

Quote example product table

We can now use this data as the source for our lookups in the Quote template, but before we do, we’re going to look at how to filter the data returned from SQL so that only in-stock items are displayed.

Click on the Filters tab in the SQL Spreads Designer.  Under the Filter Type option, we can select ‘Column’ or ‘Custom SQL’.  We’re going to select ‘Custom SQL’ because we need to run a SQL query that will return only items in stock, and that means we need to join the Product table to the ProductInventory table.

Quote example custom filter

When you click the ‘Custom SQL’ option, a text box is displayed where you can enter the SQL query.  For our use case, we want to return a list of products via a join query, we’ll need to use a Sub Query.  So, we need to paste the following:

Name  in (SELECT P.Name AS Product
FROM AdventureWorks.Production.Product AS P
JOIN AdventureWorks.Production.ProductInventory AS PI ON P.ProductID = PI.ProductID
JOIN AdventureWorks.Production.Location AS L ON PI.LocationID = L.LocationID
where L.Name = 'Finished Goods Storage' AND PI.Quantity > 0
GROUP BY P.Name, P.ListPrice)

in the Custom SQL box:

Quote example custom filter query

When you click ‘Save’, the data in the Product table is reduced to the filtered records. Finally, we’re going to update the named range that was used by the data validation lookups in the Quote sheet:

Quote example update named range

And, we also need to update the XLOOKUP function that the Quote sheet uses to get the price when a user selects an item – it needs to reference the new Table2 which is the data from SQL Server.

Quote example update lookup function

That’s it!  Our Sales Reps can now create quotes based on up-to-the-minute prices for items that are currently in stock.  Each time the Sales Rep opens the spreadsheet, the data will be refreshed from SQL Server.

Bonus Feature!  Update prices in Excel and save to SQL Server

We have connected Excel to SQL Server so that our Sales Reps can create quotes based on up-to-the-minute prices and availability.

We can go one step further and provide the ability for a designated user (eg an Administrator) to update the Sales Prices of the items directly in Excel, and have the updates saved back to the ‘Production.Product’ table in SQL Server.

For example, if I wanted to change the price of the first item in the list to $39.99, I can type in the ListPrice cell and click ‘Save to Database’ – it’s that easy!  Of course, we would want this capability locked down to certain users only, and this is easily done through SQL Spreads.

Quote example update price

Summary

In this article, we’ve shown how easy it is to connect Excel to SQL Server using the SQL Spreads Add-In.  We also went through an example to show how a simple quotes spreadsheet can use up-to-date sales price data from a SQL database, and how the prices in the database can also be updated directly from Excel.

Download the trial version of SQL Spreads and connect Excel to SQL Server today.

*This article was originally published on June 29, 2021 and was updated on May 6, 2022 to include some new screenshots.

Andy

Andy McDonald

Andy has worked 20+ years in the Engineering, Financial, and IT sectors with data analysis and presentation using tools such as SQL Server, Excel, Power Query and Power BI.

Writes for SQL Spreads about Excel and SQL Server and how to tie those two together.

Провайдеры данных

Для работы с Excel 2003 (.Xls) можно использовать провайдер Microsoft Jet OLE DB 4.0.

SELECT * FROM OPENROWSET(
	'Microsoft.Jet.OLEDB.4.0', 
	'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1', 
	'SELECT * FROM [Sheet1$]');

Для работы с Excel 2007 (.Xlsx) — Microsoft ACE OLEDB 12.0.

SELECT * FROM OPENROWSET (
    'Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1',
    'SELECT * FROM [Sheet1$]');

В Windows 10 открыть настройки источников данных ODBC можно написав «Источники данных ODBC» или через Панель управления Администрирование.

Extended Properties

  • HDR=YES|NO. HDR=YES означает, что первую строку листа, следует рассматривать как заголовки колонок. Т.о. значение из первой строки можно использовать как имена полей в sql запросах (любых: select, insert, update, delete).
  • IMEX=1|3. 1 — открыть соединение для чтения. 3 — для записи.

Создание Linked Server в Sql Server для доступа к Excel

EXEC sp_addLinkedServer
    @server= N'XLSX_2010',
    @srvproduct = N'Excel',
    @provider = N'Microsoft.ACE.OLEDB.12.0',
    @datasrc = N'd:tmpTimeSheets.xlsx',
    @provstr = N'Excel 12.0; HDR=Yes';
GO

После создания связанного сервера можно будет просмотреть имена доступных листов.

Затем, чтобы обратиться к сервису:

SELECT * FROM OPENQUERY (XLSX_2010, 'Select * from [Sheet1$]')
или
SELECT * FROM [XLSX_2010]...[Лист1$]

Обращение к лиcтам, диапазонам, полям

Для обращения к листу из SQL запроса нужно использовать имя листа, например: [Sheet1$] или [Лист1$]. Обращение к диапазону: [Sheet1$A16:F16].

Вставка данных в произвольное место

Примеры указания диапазона при вставке строк (insert)

  • [table1$B4:E20]
  • [table1$S4:U]
  • [table1$F:G]

При вставке должны выполняться следующие условия:

  • Первая строчка указанного диапазона дожна входить в диапазон ячеек с данными. Чтобы создать на листе диапазон с данными достаточно в углах некоторого прямоугольного диапазона (в левом верхнем и правом нижнем) вписать значение (C4:I7 на скриншоте). Т.е. сама первая строчка указанного в insert диапазона данные содержать не обязана, достаточно, чтобы она просто входила в такой диапазон. Иначе возникнет ошибка "This table contains cells that are outside the range of cells defined in this spreadsheet"
  • Хвост диапазона должен содержать пустые строки (хотя бы одну).

Пример: Дан лист, где заполнены только 2 ячейки: C4, I7. После выполнения команды INSERT INTO [table1$E6:G] VALUES(2, 'FF','2014-01-03') результат будет как на скриншоте. Поясним: строка E6:G6 является первой строкой диапазона для вставки. Она входит в заполненный диапазон C4:I7. Поэтому данные были вставлены на следующей пустой строке — 8. Из этого примера становится ясно, что через OleDb нельзя работать с несколькими независимыми диапазонами на одном листе, используя вставку (update будет работать).

Insert

Ошибки

  • System.Data.OleDb.OleDbException (0x80004005): Operation must use an updateable query. Соединение открыто для чтение, при этом происходит попытка внести изменения (выполнить insert, update или delete). Решение: открыть соединение для записи, установив свойство провайдера в строке соединения IMEX=3 (см. выше).
  • System.Data.OleDb.OleDbException (0x80004005): "This table contains cells that are outside the range of cells defined in this spreadsheet". Такая ошибка возникает при подпытке обновить (update) или вставить (insert) значения в диапазоне, в котором отсутствуют данные на листе.
    1. Если нужно произвести запись в определенные ячейки инструкцией update, то

Ссылки

  • https://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
  • https://stackoverflow.com/questions/36987636/cannot-create-an-instance-of-ole-db-provider-microsoft-jet-oledb-4-0-for-linked
  • https://stackoverflow.com/questions/26267224/the-ole-db-provider-microsoft-ace-oledb-12-0-for-linked-server-null
  • http://www.ashishblog.com/importexport-excel-xlsx-or-xls-file-into-sql-server/
  • https://yoursandmyideas.com/2011/02/05/how-to-read-or-write-excel-file-using-ace-oledb-data-provider/
  • https://stackoverflow.com/questions/46373895/how-to-open-a-huge-excel-file-efficiently Несколько способов открыть большой Excel файл, в т.ч. с помощью OleDb.

Понравилась статья? Поделить с друзьями:
  • Links to files in excel
  • Link doc in word
  • Links to documents in word
  • Link data from excel to excel
  • Links not breaking in excel