Python library for seamless bidirectional communication between Python and Excel across Windows and macOS platforms.
Commercial features including reports system, embedded code, additional engines, and xlwings Server integration. xlwings PRO extends the open-source version with advanced capabilities for enterprise deployment, web integration, and enhanced performance.
Template-based Excel report generation using Jinja2 templating engine for dynamic content creation.
# Available in xlwings.reports module (PRO only)
def create_report(template_path: str, output_path: str, **data):
"""
Generate Excel report from template with data substitution.
Args:
template_path (str): Path to Excel template file (.xlsx).
output_path (str): Path for generated report output.
**data: Data dictionary for template variable substitution.
Examples:
# Create quarterly report
xw.reports.create_report(
'templates/quarterly_template.xlsx',
'reports/Q1_2024_report.xlsx',
quarter='Q1 2024',
sales_data=sales_df,
charts=chart_data
)
"""
def render_template(template: str, **data):
"""
Render Jinja2 template string with provided data.
Args:
template (str): Jinja2 template string.
**data: Data for template rendering.
Returns:
str: Rendered template content.
Examples:
result = xw.reports.render_template(
"Sales for {{ quarter }}: {{ sales | sum }}",
quarter="Q1",
sales=[100, 200, 300]
)
"""Reports usage examples:
import xlwings as xw
import pandas as pd
# Template Excel file contains Jinja2 placeholders:
# Cell A1: {{ company_name }}
# Cell A2: Sales Report for {{ period }}
# Range A5: {{ sales_data }}
# Generate report with data
quarterly_data = pd.DataFrame({
'Month': ['Jan', 'Feb', 'Mar'],
'Sales': [10000, 12000, 15000],
'Target': [9000, 11000, 14000]
})
xw.reports.create_report(
template_path='templates/sales_template.xlsx',
output_path='reports/Q1_sales.xlsx',
company_name='Acme Corp',
period='Q1 2024',
sales_data=quarterly_data,
total_sales=quarterly_data['Sales'].sum(),
performance=quarterly_data['Sales'].sum() / quarterly_data['Target'].sum()
)
# Advanced template with conditional logic
template_content = """
{% if performance > 1.0 %}
Excellent performance: {{ performance | round(2) }}x target achieved!
{% else %}
Performance: {{ performance | round(2) }}x target ({{ shortfall }} below target)
{% endif %}
"""
result = xw.reports.render_template(
template_content,
performance=1.15,
shortfall=0
)Server-based Excel automation that doesn't require local Excel installation.
# Available in xlwings.server module (PRO only)
def script(f):
"""
Decorator to create server-compatible scripts.
Args:
f (callable): Function to run on xlwings Server.
Returns:
callable: Server-compatible function.
"""
def func(f):
"""
Decorator to create server-compatible UDFs.
Args:
f (callable): Function to create as server UDF.
Returns:
callable: Server UDF function.
"""
def arg(*args, **kwargs):
"""
Server-compatible argument decorator.
Args:
*args, **kwargs: Argument conversion specifications.
Returns:
callable: Argument decorator for server functions.
"""
def ret(*args, **kwargs):
"""
Server-compatible return value decorator.
Args:
*args, **kwargs: Return value conversion specifications.
Returns:
callable: Return value decorator for server functions.
"""Server integration examples:
import xlwings as xw
from xlwings.server import script, func, arg, ret
# Server script (no local Excel required)
@script
def process_sales_data():
"""Process sales data on xlwings Server."""
# This runs on the server, not locally
wb = xw.books.active
ws = wb.sheets['Sales']
# Process data on server
data = ws.range('A1:D100').value
processed = analyze_sales(data) # Custom analysis function
# Write results back
ws.range('F1').value = processed
return "Processing complete"
# Server UDF (works in web Excel)
@func
@arg('data', convert='dataframe')
@ret(expand='table')
def server_analyze(data):
"""UDF that runs on xlwings Server."""
return data.describe() # Statistical summary
# Deploy to server
# xlwings server deploy --script sales_processor.pyPRO-only Excel engines for specialized use cases and enhanced performance.
# Remote Engine - xlwings Server integration
from xlwings.pro import _xlremote
remote_engine = xw.Engine(impl=_xlremote.engine)
# Office.js Engine - Web Excel integration
from xlwings.pro import _xlofficejs
officejs_engine = xw.Engine(impl=_xlofficejs.engine)
# Calamine Engine - High-performance Excel file reading
from xlwings.pro import _xlcalamine
calamine_engine = xw.Engine(impl=_xlcalamine.engine)Engine usage examples:
import xlwings as xw
# Use Calamine engine for fast file reading
if 'calamine' in [e.name for e in xw.engines]:
xw.engines.active = xw.engines['calamine']
# Fast read of large Excel files
wb = xw.books.open('large_dataset.xlsx')
data = wb.sheets[0].used_range.value # Much faster than COM
# Process data without Excel GUI overhead
processed_data = analyze_large_dataset(data)
# Use Office.js engine for web Excel
if 'officejs' in [e.name for e in xw.engines]:
xw.engines.active = xw.engines['officejs']
# Works in Excel Online/Office 365
wb = xw.books.active # Current web workbook
ws = wb.sheets.active
ws.range('A1').value = 'Hello from Python in web Excel!'
# Use Remote engine for server-based automation
if 'remote' in [e.name for e in xw.engines]:
xw.engines.active = xw.engines['remote']
# Connects to xlwings Server
wb = xw.books.add() # Creates workbook on server
ws = wb.sheets[0]
ws.range('A1').value = 'Server-side Excel automation'Embed Python code directly within Excel files for portable, self-contained solutions.
# Available in xlwings.pro.embedded_code module (PRO only)
def dump(code: str, book: Book):
"""
Embed Python code into Excel workbook.
Args:
code (str): Python code to embed.
book (Book): Target Excel workbook.
Examples:
# Embed analysis code in workbook
analysis_code = '''
import pandas as pd
def analyze_data():
ws = xw.sheets.active
data = ws.range("A1:D100").value
df = pd.DataFrame(data[1:], columns=data[0])
return df.describe()
'''
wb = xw.books.active
xw.pro.embedded_code.dump(analysis_code, wb)
"""
def load(book: Book) -> str:
"""
Extract embedded Python code from Excel workbook.
Args:
book (Book): Excel workbook containing embedded code.
Returns:
str: Extracted Python code.
Examples:
wb = xw.books.open('analysis.xlsm')
embedded_code = xw.pro.embedded_code.load(wb)
exec(embedded_code) # Execute embedded code
"""Embedded code examples:
import xlwings as xw
# Create self-contained Excel solution
wb = xw.books.add()
ws = wb.sheets[0]
# Add sample data
ws.range('A1:C4').value = [
['Product', 'Sales', 'Profit'],
['A', 1000, 200],
['B', 1500, 300],
['C', 800, 150]
]
# Python code to embed
embedded_analysis = '''
import xlwings as xw
import pandas as pd
def run_analysis():
"""Embedded analysis function."""
ws = xw.sheets.active
# Read data
data = ws.range('A1:C4').value
df = pd.DataFrame(data[1:], columns=data[0])
# Perform analysis
total_sales = df['Sales'].sum()
total_profit = df['Profit'].sum()
profit_margin = total_profit / total_sales
# Write results
ws.range('E1').value = 'Analysis Results'
ws.range('E2').value = f'Total Sales: ${total_sales:,.2f}'
ws.range('E3').value = f'Total Profit: ${total_profit:,.2f}'
ws.range('E4').value = f'Profit Margin: {profit_margin:.2%}'
return "Analysis complete"
# Auto-run analysis when workbook opens
def auto_open():
run_analysis()
'''
# Embed the code
xw.pro.embedded_code.dump(embedded_analysis, wb)
# Save as macro-enabled workbook
wb.save('self_contained_analysis.xlsm')
# Later, load and execute embedded code
wb_loaded = xw.books.open('self_contained_analysis.xlsm')
code = xw.pro.embedded_code.load(wb_loaded)
exec(code) # Runs the embedded analysisHigh-performance Excel file reading using Rust-based Calamine engine.
import xlwings as xw
# Configure Calamine engine for optimal performance
if 'calamine' in [e.name for e in xw.engines]:
# Switch to Calamine engine
original_engine = xw.engines.active
xw.engines.active = xw.engines['calamine']
try:
# Read large files efficiently
wb = xw.books.open('huge_dataset.xlsx')
# Calamine excels at reading large ranges quickly
all_data = wb.sheets[0].used_range.value
# Process multiple sheets
sheet_data = {}
for sheet in wb.sheets:
sheet_data[sheet.name] = sheet.used_range.value
# Calamine is read-only, so switch back for writing
wb.close()
xw.engines.active = original_engine
# Process and write results with regular engine
result_wb = xw.books.add()
result_wb.sheets[0].range('A1').value = all_data
finally:
# Always restore original engine
xw.engines.active = original_enginePRO features for enterprise deployment and management.
# License management
def check_pro_license():
"""Check if PRO license is active."""
return xw.__pro__
# Server deployment
def deploy_to_server(script_path, server_config):
"""Deploy xlwings script to server."""
# Server deployment logic
if not xw.__pro__:
raise xw.LicenseError("PRO license required for server deployment")
# Deploy script to xlwings Server
# Implementation depends on server configuration
# Advanced authentication
def setup_enterprise_auth(auth_config):
"""Setup enterprise authentication."""
# Enterprise SSO integration
# LDAP/Active Directory integration
# API key management
pass
# Audit and logging
def enable_audit_logging(log_config):
"""Enable comprehensive audit logging for compliance."""
# Log all Excel operations
# Track data access and modifications
# Generate compliance reports
passPRO features require a valid license key:
import xlwings as xw
# Check PRO status
if xw.__pro__:
print("xlwings PRO is active")
# PRO features available
else:
print("xlwings PRO not available")
# Only open-source features available
# License activation (via CLI)
# xlwings license activate YOUR-LICENSE-KEY
# Programmatic license check
def require_pro_license(func):
"""Decorator to require PRO license."""
def wrapper(*args, **kwargs):
if not xw.__pro__:
raise xw.LicenseError(
"This feature requires xlwings PRO. "
"Visit https://www.xlwings.org for licensing."
)
return func(*args, **kwargs)
return wrapper
@require_pro_license
def advanced_analysis():
"""Function requiring PRO license."""
return "Advanced analysis with PRO features"import xlwings as xw
from xlwings.server import script
# PRO-powered data processing pipeline
@script # Runs on xlwings Server
def monthly_report_pipeline():
"""Complete monthly reporting pipeline."""
# Step 1: Fast data loading with Calamine
xw.engines.active = xw.engines['calamine']
source_wb = xw.books.open('monthly_data.xlsx')
raw_data = source_wb.sheets[0].used_range.value
source_wb.close()
# Step 2: Switch to regular engine for processing
xw.engines.active = xw.engines['excel']
# Step 3: Generate report using templates
processed_data = process_monthly_data(raw_data)
xw.reports.create_report(
template_path='templates/monthly_template.xlsx',
output_path='reports/monthly_report.xlsx',
data=processed_data,
report_date=datetime.now().strftime('%Y-%m-%d')
)
# Step 4: Embed analysis code for interactivity
report_wb = xw.books.open('reports/monthly_report.xlsx')
interactive_code = '''
def refresh_charts():
# Code for refreshing charts with new data
pass
def drill_down_analysis(category):
# Code for detailed analysis
pass
'''
xw.pro.embedded_code.dump(interactive_code, report_wb)
report_wb.save()
return "Monthly report generation complete"
# Deploy to server
# xlwings server deploy --script monthly_pipeline.py# PRO-specific types
PRORlicense = bool # PRO license status
ServerScript = Callable[[], Any] # Server-compatible script
ServerUDF = Callable[..., Any] # Server-compatible UDF
# Reports types
TemplatePath = str # Path to Excel template file
OutputPath = str # Path for generated report
TemplateData = dict[str, Any] # Data for template rendering
JinjaTemplate = str # Jinja2 template string
# Embedded code types
EmbeddedCode = str # Python code to embed
CodeBook = Book # Workbook containing embedded code
# Engine types
RemoteEngine = Engine # xlwings Server engine
OfficeJSEngine = Engine # Office.js web engine
CalamineEngine = Engine # Rust-based reader engine
# Server types
ServerConfig = dict[str, Any] # Server configuration
AuthConfig = dict[str, Any] # Authentication configuration
DeploymentConfig = dict[str, Any] # Deployment settingsInstall with Tessl CLI
npx tessl i tessl/pypi-xlwings