How to use Workbooks.OpenDatabase in the xlwings API way

The OpenDatabase member of the Workbooks object in the Excel object model is a method used to connect to and import data from an external database directly into Excel. This functionality is particularly valuable for automating data retrieval from sources like Microsoft Access, SQL Server, or other ODBC-compliant databases, enabling dynamic report generation and data analysis without manual copy-paste operations. In xlwings, this method provides a programmatic way to execute such database queries through Excel’s engine, leveraging its native data connection capabilities.

Syntax and Parameters

In xlwings, the method is accessed via the api property of an Excel App or Book object. The typical call pattern is:

workbook.api.OpenDatabase(Connection, CommandText, CommandType, BackgroundQuery, ImportDataAs)

The parameters map closely to the VBA Workbooks.OpenDatabase method. Below is a detailed breakdown:

ParameterDescriptionTypical Values / How to Specify
ConnectionA string that defines the connection to the database. This includes the data source and any necessary credentials.For an Access database: "DSN=MS Access Database;DBQ=C:\\path\\database.accdb;". For SQL Server: "ODBC;DSN=MyServerDSN;UID=user;PWD=password;".
CommandTextThe SQL query string or the name of a table, query, or stored procedure to run."SELECT * FROM SalesData" or "TableName".
CommandTypeSpecifies the type of command in CommandText.Use Excel constants: xlwings.constants.xlCmdTable (default for table names), xlwings.constants.xlCmdSql (for SQL strings).
BackgroundQueryA boolean that determines if the query runs asynchronously.True for background (asynchronous) query, False (default) for foreground.
ImportDataAsDefines how the returned data is placed.A Workbook object or xlwings.constants.xlPTTable. Often set as the workbook itself: wb.api for a new workbook, or a specific Range object like sheet.range('A1').api to import to a specific location.

Important Notes on xlwings Usage:

  • The method is called on the api property because OpenDatabase is a method of the underlying COM object (Excel’s VBA object model).
  • You often need to import xlwings.constants to use the Excel constants for parameters like CommandType.
  • The Connection string must be correctly formatted for your specific database provider (ODBC, OLE DB). Incorrect strings are a common source of errors.

Code Examples

  1. Basic Example: Importing a Table from Microsoft Access into a New Workbook
    This example opens a connection to an Access database and imports an entire table named “Customers”.
import xlwings as xw
import xlwings.constants as xl

# Launch Excel app
app = xw.App(visible=True)
# Create a new, empty workbook
wb = app.books.add()

# Define the connection string (adjust the DBQ path)
connection_str = "DSN=MS Access Database;DBQ=C:\\Data\\MyDatabase.accdb;"

# Use the OpenDatabase method on the workbook's API
# This imports the 'Customers' table into the active sheet starting at cell A1
wb.api.OpenDatabase(
Connection=connection_str,
CommandText="Customers",
CommandType=xl.xlCmdTable,
BackgroundQuery=False,
ImportDataAs=wb.sheets.active.range('A1').api
)
  1. Example with SQL Query and Importing to a Specific Location
    This example runs a custom SQL query on a SQL Server database via an ODBC DSN and places the results into a specific range on a sheet named “Report”.
import xlwings as xw
import xlwings.constants as xl

# Connect to an existing workbook
wb = xw.Book("Monthly_Report.xlsx")
report_sheet = wb.sheets["Report"]
target_range = report_sheet.range("B5")

# Define ODBC connection string (DSN must be pre-configured on the system)
connection_str = "ODBC;DSN=MyCompanySQLServer;UID=analyst;PWD=secure_pwd;"

# Define the SQL command
sql_query = """
SELECT Region, Product, SUM(Sales) AS TotalSales
FROM SalesTransactions
WHERE TransactionDate >= '2024-01-01'
GROUP BY Region, Product
ORDER BY Region, TotalSales DESC
"""

# Execute the query
wb.api.OpenDatabase(
Connection=connection_str,
CommandText=sql_query,
CommandType=xl.xlCmdSql, # Explicitly state it's a SQL command
BackgroundQuery=True, # Run in the background to not block Excel
ImportDataAs=target_range.api
)

# Optional: Wait for the background query to complete if needed
# while report_sheet.api.QueryTables(1).Refreshing:
# xw.time.sleep(0.1)

August 8, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *