Update excel with sql

Every week, my analysts have a spreadsheet of invoices which they need to update with a check number and check date. The checks table exists in SQL server.

I’ve written them a macro that iterates through each row of the spreadsheet, opens an ADO recordset using a statement like this:

SELECT CheckNumber, CheckDate FROM CHECKS WHERE Invoice_Number = " & cells (i,2)

… and then uses the fields from the recordset to write the number and date to the first two columns of that row in the Excel spreadsheet.

The code performs acceptably for a few hundred rows, but is slow when there are thousands of rows.

Is there a faster way to update an Excel spreadsheet than with a row-by-row lookup using ADO? For example, is there a way to do a SQL join between the spreadsheet and the table in SQL Server?

Edit: In response to Jeeped’s questions, here’s a bit of clarification.

What I’m really trying to do is find a way to «batch» update an Excel spreadsheet with information from SQL server, instead executing SQL lookups and writing the results a row at a time. Is there a way to do the equivalent of a join and return the entire results set in a single recordset?

The Invoice example above really represents a class of problems that I encounter daily. The end users have a spreadsheet that contains their working data (e.g. invoices) and they want me to add information from a SQL server table to it. For example, «Using the invoice number in column C, add the check number for that invoice in column A, and the check date in column B». Another example might be «For each invoice in column b, add the purchase order number to column a.»

The Excel source column would be either a number or text. The «match» column in the SQL table would be of a corresponding data type, either varchar or integer. The data is properly normalized, indexed, etc. The updates would normally affect a few hundred or thousand rows, although sometimes there will be as many as twenty to thirty thousand.

If I can find a way to batch rows, I’ll probably turn this into an Excel add-in to simplify the process. For that reason, I’d like to stay in VBA because my power users can extend or modify it to meet their needs—I’d rather not write it in a .NET language because then we need to dedicate developer time to modifying and deploying it. The security of the Excel application is not a concern here because the users already have access to the data through ODBC linked tables in an MS Access database and we have taken appropriate security precautions on the SQL Server.

Moving the process to SSIS would require a repeatability that doesn’t exist in the actual business process.

Содержание

  1. What is the fastest way to update a worksheet from SQL Server
  2. Update Excel from SQL server
  3. Insert, Update or Delete Data in SQL Server from Excel
  4. Prerequisites
  5. OPENROWSET Examples
  6. SELECT with a JOIN and ORDER BY Clause
  7. INSERT with a SELECT Statement
  8. UPDATE with a JOIN Statement
  9. DELETE with a JOIN Statement
  10. General Analysis
  11. Update excel from sql server
  12. Answered by:
  13. Question
  14. Answers
  15. Import data from Excel to SQL Server or Azure SQL Database
  16. List of methods
  17. Import and Export Wizard
  18. Integration Services (SSIS)
  19. OPENROWSET and linked servers
  20. Distributed queries
  21. Linked servers
  22. Prerequisite — Save Excel data as text
  23. The Import Flat File Wizard
  24. BULK INSERT command
  25. BCP tool
  26. Copy Wizard (ADF)
  27. Azure Data Factory
  28. Common errors
  29. Microsoft.ACE.OLEDB.12.0″ has not been registered
  30. Cannot create an instance of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»
  31. The 32-bit OLE DB provider «Microsoft.ACE.OLEDB.12.0» cannot be loaded in-process on a 64-bit SQL Server
  32. The OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)» reported an error.
  33. Cannot initialize the data source object of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»

What is the fastest way to update a worksheet from SQL Server

Every week, my analysts have a spreadsheet of invoices which they need to update with a check number and check date. The checks table exists in SQL server.

I’ve written them a macro that iterates through each row of the spreadsheet, opens an ADO recordset using a statement like this:

. and then uses the fields from the recordset to write the number and date to the first two columns of that row in the Excel spreadsheet.

The code performs acceptably for a few hundred rows, but is slow when there are thousands of rows.

Is there a faster way to update an Excel spreadsheet than with a row-by-row lookup using ADO? For example, is there a way to do a SQL join between the spreadsheet and the table in SQL Server?

Edit: In response to Jeeped’s questions, here’s a bit of clarification.

What I’m really trying to do is find a way to «batch» update an Excel spreadsheet with information from SQL server, instead executing SQL lookups and writing the results a row at a time. Is there a way to do the equivalent of a join and return the entire results set in a single recordset?

The Invoice example above really represents a class of problems that I encounter daily. The end users have a spreadsheet that contains their working data (e.g. invoices) and they want me to add information from a SQL server table to it. For example, «Using the invoice number in column C, add the check number for that invoice in column A, and the check date in column B». Another example might be «For each invoice in column b, add the purchase order number to column a.»

The Excel source column would be either a number or text. The «match» column in the SQL table would be of a corresponding data type, either varchar or integer. The data is properly normalized, indexed, etc. The updates would normally affect a few hundred or thousand rows, although sometimes there will be as many as twenty to thirty thousand.

If I can find a way to batch rows, I’ll probably turn this into an Excel add-in to simplify the process. For that reason, I’d like to stay in VBA because my power users can extend or modify it to meet their needs—I’d rather not write it in a .NET language because then we need to dedicate developer time to modifying and deploying it. The security of the Excel application is not a concern here because the users already have access to the data through ODBC linked tables in an MS Access database and we have taken appropriate security precautions on the SQL Server.

Moving the process to SSIS would require a repeatability that doesn’t exist in the actual business process.

Источник

Update Excel from SQL server

September 26, 2003 at 3:36 am

I need to update an excel sheet with sql query result.

September 26, 2003 at 7:42 am

Can you be more specific.

Do you want Excel to update the worksheet or for sql to create the worksheet?

Far away is close at hand in the images of elsewhere.
Anon.

September 26, 2003 at 7:46 am

Ooops!

Just noticed this is in the DTS section and therefore assume you want to DTS to Excel.

You can either DTS direct to Excel but there are data/null problems or you could DTS to a csv file and open it with Excel.

Edited by — davidburrows on 09/26/2003 07:46:43 AM

Far away is close at hand in the images of elsewhere.
Anon.

September 29, 2003 at 1:51 am

hello! I have a sheet excel and I have to update particular cells of the sheet with the result of a sql query. I have found some example but I would want to index the cells that I want to update for example

Update Prova. Foglio set $A$1 = ‘pippo’

Can you be more specific.

Do you want Excel to update the worksheet or for sql to create the worksheet?

September 29, 2003 at 2:31 am

Based upon your example you are using Linked Server to access Excel. When doing this sql does not know it is Excel (this is handled by the driver) and will treat each worksheet as a table with first row as column names. You can update worksheets by using

SQL will not recognise $A$1 as this is Excel.

The only way I can see to enable you to update the spreadsheet is to write a macro in the workbook that gets the results of the query and updates cells. Or create an ActiveX script to use Excel’s objects.

Edited by — davidburrows on 09/29/2003 02:31:11 AM

Far away is close at hand in the images of elsewhere.
Anon.

Источник

Insert, Update or Delete Data in SQL Server from Excel

Problem

I have seen your previous tips (Export data from SQL Server to Excel and Different Options for Importing Data into SQL Server) related to working with Excel and SQL Server data. The main command used in one of the tips is OPENROWSET. This has been beneficial for us because in our environment because our business users provide data to us in the form of Excel spreadsheets. Many of the situations end up translating to INSERT, UPDATE or DELETE code in one or more of our SQL Server databases. We always upload the data to a table and then begin the process. Although this process works are you familiar with any other options to directly perform the INSERT, UPDATE or DELETE operations? Are their any benefits to transitioning our code to another approach with the OPENROWSET command?

Solution

Yes — You are correct the OPENROWSET command can directly support INSERT, UPDATE or DELETE operations as shown in these tips: Export data from SQL Server to Excel and Different Options for Importing Data into SQL Server. In addition, the OPENROWSET command can also support SELECT statements where a table is joined to the Excel spreadsheet. Let’s work through some examples with the SQL Server 2005 AdventureWorks sample database for each operation with a sample Excel spreadsheet.

Prerequisites

For all of these examples, please do the following:

  • Download this Excel (Office 2003) spreadsheet to perform the operations.
  • In order to follow the examples, be sure to save the Excel spreadsheet into a directory called C:MSSQLTips.
  • Review each of the worksheets in the Excel file to see the different data.
  • Be sure to close the Excel spreadsheet before running any of the code.
  • Review each of the commands below before executing them in your environment.

OPENROWSET Examples

Below are four examples to show some of the flexibility with the OPENROWSET command:

SELECT with a JOIN and ORDER BY Clause

Code Explanation — With the query below, 5 records should be returned to show a simple INNER JOIN statement can return a single result set from both data in the table ([Sales].[SalesPerson]) and Excel spreadsheet.

INSERT with a SELECT Statement

Code Explanation — With the first block of code, five records are inserted into the [AdventureWorks].[Sales].[SalesPerson] table by reading the data from the INSERT_Example worksheet of the Excel spreadsheet. In the second query, the data inserted is verified.

UPDATE with a JOIN Statement

Code Explanation — With the first block of code, five records are updated in the [AdventureWorks].[Sales].[SalesPerson] table by reading the data from the UPDATE_Example worksheet of the Excel spreadsheet. In the second query, the data updated is verified.

DELETE with a JOIN Statement

Code Explanation — With the first block of code, five records are deleted in the [AdventureWorks].[Sales].[SalesPerson] table by reading the data from the DELETE_Example worksheet of the Excel spreadsheet. In the second query, the data deleted is verified.

General Analysis

In terms of transitioning your code to the new approach, I have yet to experience any performance issues with 1000’s of records, but that seems to be the first concern. If you test the approach and the overall performance is not an issue, then consider the approach. It also may be faster to perform a single UPDATE as is the case with the example above versus uploading (INSERT. SELECT) the data and then performing an UPDATE based on the new table. In addition, by using the commands listed above versus a two step process the overall code may be a little bit cleaner. A second consideration with SQL Server 2005 is that the Surface Area Configuration setting must be enabled to use this code in either case. Finally, with either approach be sure to clean up any Excel spreadsheets or temporary tables once you are finished with them.

Источник

Update excel from sql server

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I am running below update statement on Excel file and giving below error.

UPdate a
SET a .comments = b.comments
FROM OPENROWSET (‘Microsoft.ACE.OLEDB.12.0′ ,’Excel 12.0;Database=C:excelexcel_file.xlsx’ ,
‘SELECT * FROM [mytable$]’ ) a INNER

JOIN localTable
ON a.id = b.id

above statement is giving below error

Msg 8152, Level 16, State 13, Line 1

String or binary data would be truncated.

The statement has been terminated.

Please note
1. I am able to access the excel file by using T_SQL
2. If i am running UPDATE on that excel without any JOIN then its working fine

Thanks in advance

Parixit

Answers

All columns in a database system typically have a max size. If you try to squeeze in more characters than the column fits, there is no automatic truncation, but you get an error. If you are prepare to accept the data loss, you need to say:

UPdate a
SET a .comments = substring(b.comments, 1, )
FROM OPENROWSET (‘Microsoft.ACE.OLEDB.12.0′ ,’Excel 12.0;Database=C:excelexcel_file.xlsx’ ,
‘SELECT * FROM [mytable$]’ ) a INNER
JOIN localTable ON a.id = b.id

The tricky part in this case can be to find out the length of the column in the Excel book, but you can try:

SELECT a .comments
INTO #temp
FROM OPENROWSET (‘Microsoft.ACE.OLEDB.12.0′ ,’Excel 12.0;Database=C:excelexcel_file.xlsx’ ,
‘SELECT * FROM [mytable$]’ ) a INNER

EXEC tempdb..sp_help #temp

Note that the output is in bytes, so if the column is nvarchar and length is reported as 8000, you should specify 4000 as the last argument to substring.

Источник

Import data from Excel to SQL Server or Azure SQL Database

Applies to: SQL Server Azure SQL Database

There are several ways to import data from Excel files to SQL Server 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 a number of methods 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 (SQL Server and SQL Database) Directly from Excel (SQL Server 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.

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 SQL Server Import and Export Wizard. You also have the option to save the settings as a SQL Server Integration Services (SSIS) package that you can customize and reuse later.

In SQL Server Management Studio, connect to an instance of the SQL Server Database Engine.

Expand Databases.

Right-click a database.

Point to Tasks.

Choose to Import Data or Export Data:

This launches the wizard:

To learn more, review:

Integration Services (SSIS)

If you’re familiar with SQL Server Integration Services (SSIS) and don’t want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

To learn more, review:

To start learning how to build SSIS packages, see the tutorial How to Create an ETL Package.

OPENROWSET and linked servers

In Azure SQL Database, you cannot import directly from Excel. You must first export the data to a text (CSV) file.

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 SQL Server, especially in automated processes or processes running in parallel, you may see unexpected results.

Distributed queries

Import data directly into SQL Server from Excel files by using the Transact-SQL OPENROWSET or OPENDATASOURCE function. This usage is called a distributed query.

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.

The following code sample uses OPENROWSET to import the data from the Excel Sheet1 worksheet into a new database table.

Here’s the same example with OPENDATASOURCE .

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

  • Distributed Queries (Distributed queries are still supported in SQL Server 2019, but the documentation for this feature has not been updated.)
  • OPENROWSET
  • OPENDATASOURCE

Linked servers

You can also configure a persistent connection from SQL Server 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 SQL Server database table named Data_ls .

You can create a linked server from SQL Server Management Studio, or by running the system stored procedure sp_addlinkedserver , as shown in the following example.

For more info about linked servers, see the following topics:

For more examples and info about both linked servers and distributed queries, see the following topic:

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.

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.

For more info and examples for SQL Server and SQL Database, see the following topics:

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 SQL Server or SQL Database from a test (CSV) file saved to local storage.

For a text (CSV) file stored in Azure Blob storage, use BULK INSERT or OPENROWSET. For an examples, see Example.

For more info about BCP, see the following topics:

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

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 SQL Server 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 topics:

To start learning how to copy data with Azure data factory, see the following topics:

Common errors

Microsoft.ACE.OLEDB.12.0″ has not been registered

This error occurs because the OLEDB provider is not installed. Install it from Microsoft Access Database Engine 2010 Redistributable. Be sure to install the 64-bit version if Windows and SQL Server are both 64-bit.

The full error is:

Cannot create an instance of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»

This indicates that the Microsoft OLEDB has not been configured properly. Run the following Transact-SQL code to resolve this:

The full error is:

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 SQL Server. 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:

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 SQL Server process and the file. Ensure that the account that is running the SQL Server service has full access permission to the file. We recommend against trying to import files from the desktop.

Источник

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.

  • Remove From My Forums
  • Question

  • I posted this in an earlier post and then realized the post was marked answered so it may be overlooked.  I am reposting a solution.

    You can connect to Excel as a database.  Items to note

    • — Used named range to define table COLOR_TABLE
    • — Careful with column names/table names — avoid reserved words.
    • — The id column is formatted as text not number.  Excel makes assumptions on column data types.  This can be a problem.
    • — Add reference to MS ADO
    • — Probably need to add better error checking.

    Option Explicit

    Dim ExcelDB As New ADODB.Connection
    Dim rst1 As New ADODB.Recordset

    Dim rCnt As Boolean

    Sub UpdateTable()
      Const wkBook As String = «C:TempUpdateTable.xls»
      Dim sql As String

     
      If ExcelConnect(wkBook) Then
        sql = «UPDATE color_table SET color_name = ‘red@’ WHERE id_num = ‘123’»
        If Not WQry(rst1, ExcelDB, sql) Then Exit Sub
      End If
    End Sub

    Function ExcelConnect(dsnWkBook As String) As Boolean

      On Error GoTo ErrorHandler:  ‘ Enable error-handling routine.
    ‘ Open Connection to Excel Spreadsheet to perform queries
      If ExcelDB.State = adStateOpen Then
        ExcelDB.Close
        Set ExcelDB = Nothing
      End If
      If Len(dsnWkBook) > 0 Then
        ExcelDB.Open «Provider=Microsoft.Jet.OLEDB.4.0;» & _
                     «Data Source=» & dsnWkBook & «;» & _
                     «Extended Properties=Excel 8.0;»
        ExcelConnect = True
      End If
      Exit Function       ‘ Exit to avoid handler.
    ErrorHandler:    ‘ Error-handling routine.
      ExcelConnect = False
    End Function

    Function WQry(gRST As ADODB.Recordset, xDB, qS As String) As Boolean

      If gRST.State = adStateOpen Then
        gRST.Close
      End If

      On Error GoTo ErrorHandler  ‘ Enable error-handling routine.

      gRST.Open qS, xDB

      WQry = True

      Exit Function     ‘ Exit to avoid handler.
    ErrorHandler:    ‘ Error-handling routine.

      Err.Clear
      WQry = False
    End Function

    Table

    ID_NUM    COLOR_NAME    LAST_UPDATE
    123    red@    12/3/2010
    102    Blue    13/04/2010
    123    red@    12/3/2010

Answers

    • Marked as answer by

      Monday, May 10, 2010 9:12 AM

  • Thanks Jeff.  Couple of items to note:

    This works without opening the database workbook.  This can be useful if you need to select data from or update numerous workbooks.    I once had a task to to get data from close to a 1000 workbooks and it was reasonably fast using this
    technique.

    There was a problem with this causing a memory leak.

    http://support.microsoft.com/default.aspx/kb/319998?p=1

    I worked with MS and they fixed the problem and provided me with a fix.  They planned on doing a production release.  I never did follow up so not sure if they did.  You have to run it a lot before there is an issue and as soon as you exit
    Excel it releases the memory so it should not be an issue for most.

    • Marked as answer by
      Tim Li
      Monday, May 10, 2010 9:12 AM

My previous article explored using plain SQL to connect and work with other Access databases:

Advanced SQL To Connect With External Databases

Everyone knows that we can create linked table to external databases, but did you know you can actually directly query another database without first setting up a linked table?

This time, I thought I’d show you how you can create SELECT statements that can bind directly to an Excel Workbook to work with the data without the need of Linked Table or advanced VBA coding.

Linked Table Limitation

Yes, it is true, you used to be able to directly edit Excel documents via linked tables, but that ability was lost/removed in Access 2003 and 2002:

Because of legal issues, Microsoft has disabled the functionality in Access 2003 and in Access 2002 that let users change the data in linked tables that point to a range in an Excel workbook.Microsoft — KB904953

This is why turning towards using a direct SQL Query can be so valuable as it allows you to still edit a Workbook directly without the need of VBA automation or some other workaround.

Basic SELECT Statement

Below is the basic syntax to perform a SELECT query on an Excel Workbook:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$];

Practical Usage Example

Here’s a concrete example:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$];

Retrieving a Specific Cell or Range

What if, instead of getting an entire sheet, you only wanted to retrieve a specific range or cell.  Well, it can be done quite easily!  You simply need to add a range definition to the sheet name, as illustrated below:

SELECT * 
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$XX:XX];

Return a Specific Range

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$C5:G17];

Return a Specific Cell

The same principle is required for a single cell, in that you still have to supply a range!  So you would do:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$C5:C5];

Applying a Where Clause

Yes, you can apply where clauses here!

SELECT * 
FROM [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$]
WHERE [ID] = 13;

Basic Append Query

Below is the basic syntax to perform an UPDATE query on an Excel Workbook:

INSERT INTO [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$] 
('Field1Name', 'Field2Name', 'Field3Name', ...)
VALUES (1, 'SomeValue', 'SomeValue');

Practical Usage Example

Here’s a simple example

INSERT INTO [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$]
( Company, [Last Name], [First Name] )
VALUES ('McDonalds', 'Kempczinski', 'Chris');

Basic Update Query

Below is the basic syntax to perform an UPDATE query on an Excel Workbook:

UPDATE [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$] 
SET [FieldName] = 'Value'
WHERE [FieldName] = 'Condition';

Practical Usage Example

Here’s a simple example

UPDATE [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$] 
SET [FirstName] = 'Christopher'
WHERE [FirstName] = 'Chris';

Basic DELETE Query

This operation cannot be performed and you will receive an error like:

Microsoft Access Deleteing data in a linked table is not supported by this ISAM.Microsoft Access

Explanation of The Parameters

In case you were wondering, IMEX refers to ‘Import Export mode’ and has 3 possible values: 0,1 or 2.
HDR refers to Header and has 2 possible values: Yes or No.

HDR (Yes/No)
This property will be used to specify the definition of header for each column. If the value is ‘Yes’, the first row will be treated as heading. Otherwise, the heading will be generated by the system like F1, F2 and so on.

IMEX (0/1/2)
IMEX refers to IMport EXport mode. This can take three possible values.

IMEX=0 and IMEX=2 will result in ImportMixedTypes being ignored and the default value of ‘Majority Types’ is used. In this case, it will take the first 8 rows and then the data type for each column will be decided.
IMEX=1 is the only way to set the value of ImportMixedTypes as Text. Here, everything will be treated as text.Gaurang Desai (on Code Project)

IMEX!

For a query to be editable, you must use an IMEX value of 0!  Otherwise, it is read-only.

A Workaround For Linked Tables

As you have seen above, to make queries directly editable, we are controlling the connection used by specifying IMEX=0.

Well, in reality we can do the same thing to a Linked Table to an Excel Worksheet.

The same issue exists with Excel Linked tables.  If you examine the connection string you will get back something like:

Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=C:DemosContacts.xlsx

where, by default, Access creates the Linked Tables with an IMEX=2 which doesn’t allow editing.  Thus, the workaround, is to change the IMEX value of the Linked table to 0.  For this I created a very simple procedure:

'---------------------------------------------------------------------------------------
' Procedure : MakeExcelLinkedTableEditable
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Update Excel Linked Tables to make them Editable
'               Change IMEX to 0
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Late Binding  -> none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTable    : Name of the Excel Linked Table to make editable
'
' Usage:
' ~~~~~~
' Call MakeExcelLinkedTableEditable("Sheet1")
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2022-02-26              Initial Public Release
'---------------------------------------------------------------------------------------
Sub MakeExcelLinkedTableEditable(ByVal sTable As String)
    On Error GoTo Error_Handler
    Dim db                    As DAO.Database
    Dim tdf                   As DAO.TableDef

    Set db = CurrentDb
    Set tdf = db.TableDefs(sTable)
    'Only IMEX=0 is editable!
    tdf.Connect = Replace(Replace(tdf.Connect, "IMEX=1", "IMEX=0"), "IMEX=2", "IMEX=0")
    tdf.RefreshLink

Error_Handler_Exit:
    On Error Resume Next
    If Not tdf Is Nothing Then Set tdf = Nothing
    If Not db Is Nothing Then Set db = Nothing
    Exit Sub

Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: MakeExcelLinkedTableEditable" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Sub

So now, you can create a Linked Table to an Excel Worksheet, run this procedure, and it becomes editable.  You can create, queries, forms and be able to work with the data.

Update 2022-03-01 — Excel Connection Fixer

You may like to review the following which offer a interactive form to make the necessary change(s) to make an Excel Linked Table editable.

Making Excel Linked Tables Editable

Many of you are aware of my previous article about linking to Excel spreadsheets In the section entitled ‘A Workaround For Linked Tables’ I provided some VBA code to change the necessary connection property. Knowing that not everyone is comfortable with VBA, I decided to quickly put together a simple form that you can import…

Continue reading

Connection Caching

One quick comment regarding working with Excel in this manner.  While playing around with all of this, trying to figure out what worked and didn’t, I found out the hard way that Microsoft Access does some type of connection caching.  So, I spent some serious time with valid code that wouldn’t work because Access continued to use an old connection I had previously tried out.  Moral of the story, learn from my mistake, close and restart Access when you modify the connection string!

A Few Resources on the Subject

I’d love to provide links to Official documentation on all of this, I have searched, yet found nothing. Lots and lots of posts, but nothing from Microsoft explicitly covering IMEX, HDR. You can find mention here and there, but never a complete authoritative official article, here are the values and what they do. I also found numerous discussions pointing to now long gone MS KB articles.

Fellow MVP Karl Donaubauer just made me aware of his post on the subject, so check that out.  Heck, I never knew he had a website with such information! I’ve provided a translated link as his site is natively German.

donkarls Access-Pages

MSAccess FAQ, Access Developer Conference, SQL Server Developer Conference, .Net Developer Conference, Database Programming Info and Downloads

Like this post? Please share to your friends:
  • Unhiding all sheets in excel
  • Update excel cells vba excel
  • Unhiding all columns in excel
  • Update dictionary in word
  • Update database with excel