0
# PRO Features
1
2
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.
3
4
## Capabilities
5
6
### Reports System
7
8
Template-based Excel report generation using Jinja2 templating engine for dynamic content creation.
9
10
```python { .api }
11
# Available in xlwings.reports module (PRO only)
12
def create_report(template_path: str, output_path: str, **data):
13
"""
14
Generate Excel report from template with data substitution.
15
16
Args:
17
template_path (str): Path to Excel template file (.xlsx).
18
output_path (str): Path for generated report output.
19
**data: Data dictionary for template variable substitution.
20
21
Examples:
22
# Create quarterly report
23
xw.reports.create_report(
24
'templates/quarterly_template.xlsx',
25
'reports/Q1_2024_report.xlsx',
26
quarter='Q1 2024',
27
sales_data=sales_df,
28
charts=chart_data
29
)
30
"""
31
32
def render_template(template: str, **data):
33
"""
34
Render Jinja2 template string with provided data.
35
36
Args:
37
template (str): Jinja2 template string.
38
**data: Data for template rendering.
39
40
Returns:
41
str: Rendered template content.
42
43
Examples:
44
result = xw.reports.render_template(
45
"Sales for {{ quarter }}: {{ sales | sum }}",
46
quarter="Q1",
47
sales=[100, 200, 300]
48
)
49
"""
50
```
51
52
Reports usage examples:
53
54
```python
55
import xlwings as xw
56
import pandas as pd
57
58
# Template Excel file contains Jinja2 placeholders:
59
# Cell A1: {{ company_name }}
60
# Cell A2: Sales Report for {{ period }}
61
# Range A5: {{ sales_data }}
62
63
# Generate report with data
64
quarterly_data = pd.DataFrame({
65
'Month': ['Jan', 'Feb', 'Mar'],
66
'Sales': [10000, 12000, 15000],
67
'Target': [9000, 11000, 14000]
68
})
69
70
xw.reports.create_report(
71
template_path='templates/sales_template.xlsx',
72
output_path='reports/Q1_sales.xlsx',
73
company_name='Acme Corp',
74
period='Q1 2024',
75
sales_data=quarterly_data,
76
total_sales=quarterly_data['Sales'].sum(),
77
performance=quarterly_data['Sales'].sum() / quarterly_data['Target'].sum()
78
)
79
80
# Advanced template with conditional logic
81
template_content = """
82
{% if performance > 1.0 %}
83
Excellent performance: {{ performance | round(2) }}x target achieved!
84
{% else %}
85
Performance: {{ performance | round(2) }}x target ({{ shortfall }} below target)
86
{% endif %}
87
"""
88
89
result = xw.reports.render_template(
90
template_content,
91
performance=1.15,
92
shortfall=0
93
)
94
```
95
96
### xlwings Server Integration
97
98
Server-based Excel automation that doesn't require local Excel installation.
99
100
```python { .api }
101
# Available in xlwings.server module (PRO only)
102
def script(f):
103
"""
104
Decorator to create server-compatible scripts.
105
106
Args:
107
f (callable): Function to run on xlwings Server.
108
109
Returns:
110
callable: Server-compatible function.
111
"""
112
113
def func(f):
114
"""
115
Decorator to create server-compatible UDFs.
116
117
Args:
118
f (callable): Function to create as server UDF.
119
120
Returns:
121
callable: Server UDF function.
122
"""
123
124
def arg(*args, **kwargs):
125
"""
126
Server-compatible argument decorator.
127
128
Args:
129
*args, **kwargs: Argument conversion specifications.
130
131
Returns:
132
callable: Argument decorator for server functions.
133
"""
134
135
def ret(*args, **kwargs):
136
"""
137
Server-compatible return value decorator.
138
139
Args:
140
*args, **kwargs: Return value conversion specifications.
141
142
Returns:
143
callable: Return value decorator for server functions.
144
"""
145
```
146
147
Server integration examples:
148
149
```python
150
import xlwings as xw
151
from xlwings.server import script, func, arg, ret
152
153
# Server script (no local Excel required)
154
@script
155
def process_sales_data():
156
"""Process sales data on xlwings Server."""
157
# This runs on the server, not locally
158
wb = xw.books.active
159
ws = wb.sheets['Sales']
160
161
# Process data on server
162
data = ws.range('A1:D100').value
163
processed = analyze_sales(data) # Custom analysis function
164
165
# Write results back
166
ws.range('F1').value = processed
167
168
return "Processing complete"
169
170
# Server UDF (works in web Excel)
171
@func
172
@arg('data', convert='dataframe')
173
@ret(expand='table')
174
def server_analyze(data):
175
"""UDF that runs on xlwings Server."""
176
return data.describe() # Statistical summary
177
178
# Deploy to server
179
# xlwings server deploy --script sales_processor.py
180
```
181
182
### Advanced Engines
183
184
PRO-only Excel engines for specialized use cases and enhanced performance.
185
186
```python { .api }
187
# Remote Engine - xlwings Server integration
188
from xlwings.pro import _xlremote
189
remote_engine = xw.Engine(impl=_xlremote.engine)
190
191
# Office.js Engine - Web Excel integration
192
from xlwings.pro import _xlofficejs
193
officejs_engine = xw.Engine(impl=_xlofficejs.engine)
194
195
# Calamine Engine - High-performance Excel file reading
196
from xlwings.pro import _xlcalamine
197
calamine_engine = xw.Engine(impl=_xlcalamine.engine)
198
```
199
200
Engine usage examples:
201
202
```python
203
import xlwings as xw
204
205
# Use Calamine engine for fast file reading
206
if 'calamine' in [e.name for e in xw.engines]:
207
xw.engines.active = xw.engines['calamine']
208
209
# Fast read of large Excel files
210
wb = xw.books.open('large_dataset.xlsx')
211
data = wb.sheets[0].used_range.value # Much faster than COM
212
213
# Process data without Excel GUI overhead
214
processed_data = analyze_large_dataset(data)
215
216
# Use Office.js engine for web Excel
217
if 'officejs' in [e.name for e in xw.engines]:
218
xw.engines.active = xw.engines['officejs']
219
220
# Works in Excel Online/Office 365
221
wb = xw.books.active # Current web workbook
222
ws = wb.sheets.active
223
ws.range('A1').value = 'Hello from Python in web Excel!'
224
225
# Use Remote engine for server-based automation
226
if 'remote' in [e.name for e in xw.engines]:
227
xw.engines.active = xw.engines['remote']
228
229
# Connects to xlwings Server
230
wb = xw.books.add() # Creates workbook on server
231
ws = wb.sheets[0]
232
ws.range('A1').value = 'Server-side Excel automation'
233
```
234
235
### Embedded Code Management
236
237
Embed Python code directly within Excel files for portable, self-contained solutions.
238
239
```python { .api }
240
# Available in xlwings.pro.embedded_code module (PRO only)
241
def dump(code: str, book: Book):
242
"""
243
Embed Python code into Excel workbook.
244
245
Args:
246
code (str): Python code to embed.
247
book (Book): Target Excel workbook.
248
249
Examples:
250
# Embed analysis code in workbook
251
analysis_code = '''
252
import pandas as pd
253
254
def analyze_data():
255
ws = xw.sheets.active
256
data = ws.range("A1:D100").value
257
df = pd.DataFrame(data[1:], columns=data[0])
258
return df.describe()
259
'''
260
261
wb = xw.books.active
262
xw.pro.embedded_code.dump(analysis_code, wb)
263
"""
264
265
def load(book: Book) -> str:
266
"""
267
Extract embedded Python code from Excel workbook.
268
269
Args:
270
book (Book): Excel workbook containing embedded code.
271
272
Returns:
273
str: Extracted Python code.
274
275
Examples:
276
wb = xw.books.open('analysis.xlsm')
277
embedded_code = xw.pro.embedded_code.load(wb)
278
exec(embedded_code) # Execute embedded code
279
"""
280
```
281
282
Embedded code examples:
283
284
```python
285
import xlwings as xw
286
287
# Create self-contained Excel solution
288
wb = xw.books.add()
289
ws = wb.sheets[0]
290
291
# Add sample data
292
ws.range('A1:C4').value = [
293
['Product', 'Sales', 'Profit'],
294
['A', 1000, 200],
295
['B', 1500, 300],
296
['C', 800, 150]
297
]
298
299
# Python code to embed
300
embedded_analysis = '''
301
import xlwings as xw
302
import pandas as pd
303
304
def run_analysis():
305
"""Embedded analysis function."""
306
ws = xw.sheets.active
307
308
# Read data
309
data = ws.range('A1:C4').value
310
df = pd.DataFrame(data[1:], columns=data[0])
311
312
# Perform analysis
313
total_sales = df['Sales'].sum()
314
total_profit = df['Profit'].sum()
315
profit_margin = total_profit / total_sales
316
317
# Write results
318
ws.range('E1').value = 'Analysis Results'
319
ws.range('E2').value = f'Total Sales: ${total_sales:,.2f}'
320
ws.range('E3').value = f'Total Profit: ${total_profit:,.2f}'
321
ws.range('E4').value = f'Profit Margin: {profit_margin:.2%}'
322
323
return "Analysis complete"
324
325
# Auto-run analysis when workbook opens
326
def auto_open():
327
run_analysis()
328
'''
329
330
# Embed the code
331
xw.pro.embedded_code.dump(embedded_analysis, wb)
332
333
# Save as macro-enabled workbook
334
wb.save('self_contained_analysis.xlsm')
335
336
# Later, load and execute embedded code
337
wb_loaded = xw.books.open('self_contained_analysis.xlsm')
338
code = xw.pro.embedded_code.load(wb_loaded)
339
exec(code) # Runs the embedded analysis
340
```
341
342
### Reader Engine (Calamine)
343
344
High-performance Excel file reading using Rust-based Calamine engine.
345
346
```python
347
import xlwings as xw
348
349
# Configure Calamine engine for optimal performance
350
if 'calamine' in [e.name for e in xw.engines]:
351
# Switch to Calamine engine
352
original_engine = xw.engines.active
353
xw.engines.active = xw.engines['calamine']
354
355
try:
356
# Read large files efficiently
357
wb = xw.books.open('huge_dataset.xlsx')
358
359
# Calamine excels at reading large ranges quickly
360
all_data = wb.sheets[0].used_range.value
361
362
# Process multiple sheets
363
sheet_data = {}
364
for sheet in wb.sheets:
365
sheet_data[sheet.name] = sheet.used_range.value
366
367
# Calamine is read-only, so switch back for writing
368
wb.close()
369
xw.engines.active = original_engine
370
371
# Process and write results with regular engine
372
result_wb = xw.books.add()
373
result_wb.sheets[0].range('A1').value = all_data
374
375
finally:
376
# Always restore original engine
377
xw.engines.active = original_engine
378
```
379
380
### Enterprise Deployment Features
381
382
PRO features for enterprise deployment and management.
383
384
```python
385
# License management
386
def check_pro_license():
387
"""Check if PRO license is active."""
388
return xw.__pro__
389
390
# Server deployment
391
def deploy_to_server(script_path, server_config):
392
"""Deploy xlwings script to server."""
393
# Server deployment logic
394
if not xw.__pro__:
395
raise xw.LicenseError("PRO license required for server deployment")
396
397
# Deploy script to xlwings Server
398
# Implementation depends on server configuration
399
400
# Advanced authentication
401
def setup_enterprise_auth(auth_config):
402
"""Setup enterprise authentication."""
403
# Enterprise SSO integration
404
# LDAP/Active Directory integration
405
# API key management
406
pass
407
408
# Audit and logging
409
def enable_audit_logging(log_config):
410
"""Enable comprehensive audit logging for compliance."""
411
# Log all Excel operations
412
# Track data access and modifications
413
# Generate compliance reports
414
pass
415
```
416
417
## Licensing and Activation
418
419
PRO features require a valid license key:
420
421
```python
422
import xlwings as xw
423
424
# Check PRO status
425
if xw.__pro__:
426
print("xlwings PRO is active")
427
# PRO features available
428
else:
429
print("xlwings PRO not available")
430
# Only open-source features available
431
432
# License activation (via CLI)
433
# xlwings license activate YOUR-LICENSE-KEY
434
435
# Programmatic license check
436
def require_pro_license(func):
437
"""Decorator to require PRO license."""
438
def wrapper(*args, **kwargs):
439
if not xw.__pro__:
440
raise xw.LicenseError(
441
"This feature requires xlwings PRO. "
442
"Visit https://www.xlwings.org for licensing."
443
)
444
return func(*args, **kwargs)
445
return wrapper
446
447
@require_pro_license
448
def advanced_analysis():
449
"""Function requiring PRO license."""
450
return "Advanced analysis with PRO features"
451
```
452
453
## Integration Examples
454
455
### Complete PRO Workflow
456
457
```python
458
import xlwings as xw
459
from xlwings.server import script
460
461
# PRO-powered data processing pipeline
462
@script # Runs on xlwings Server
463
def monthly_report_pipeline():
464
"""Complete monthly reporting pipeline."""
465
466
# Step 1: Fast data loading with Calamine
467
xw.engines.active = xw.engines['calamine']
468
source_wb = xw.books.open('monthly_data.xlsx')
469
raw_data = source_wb.sheets[0].used_range.value
470
source_wb.close()
471
472
# Step 2: Switch to regular engine for processing
473
xw.engines.active = xw.engines['excel']
474
475
# Step 3: Generate report using templates
476
processed_data = process_monthly_data(raw_data)
477
478
xw.reports.create_report(
479
template_path='templates/monthly_template.xlsx',
480
output_path='reports/monthly_report.xlsx',
481
data=processed_data,
482
report_date=datetime.now().strftime('%Y-%m-%d')
483
)
484
485
# Step 4: Embed analysis code for interactivity
486
report_wb = xw.books.open('reports/monthly_report.xlsx')
487
488
interactive_code = '''
489
def refresh_charts():
490
# Code for refreshing charts with new data
491
pass
492
493
def drill_down_analysis(category):
494
# Code for detailed analysis
495
pass
496
'''
497
498
xw.pro.embedded_code.dump(interactive_code, report_wb)
499
report_wb.save()
500
501
return "Monthly report generation complete"
502
503
# Deploy to server
504
# xlwings server deploy --script monthly_pipeline.py
505
```
506
507
## Types
508
509
```python { .api }
510
# PRO-specific types
511
PRORlicense = bool # PRO license status
512
ServerScript = Callable[[], Any] # Server-compatible script
513
ServerUDF = Callable[..., Any] # Server-compatible UDF
514
515
# Reports types
516
TemplatePath = str # Path to Excel template file
517
OutputPath = str # Path for generated report
518
TemplateData = dict[str, Any] # Data for template rendering
519
JinjaTemplate = str # Jinja2 template string
520
521
# Embedded code types
522
EmbeddedCode = str # Python code to embed
523
CodeBook = Book # Workbook containing embedded code
524
525
# Engine types
526
RemoteEngine = Engine # xlwings Server engine
527
OfficeJSEngine = Engine # Office.js web engine
528
CalamineEngine = Engine # Rust-based reader engine
529
530
# Server types
531
ServerConfig = dict[str, Any] # Server configuration
532
AuthConfig = dict[str, Any] # Authentication configuration
533
DeploymentConfig = dict[str, Any] # Deployment settings
534
```