Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Automate live Excel workbooks with xlwings—VBA execution, dashboard updates, chart automation, and real-time data.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2# ═══════════════════════════════════════════════════════════════════════════════3# CLAUDE OFFICE SKILL - Enhanced Metadata v2.04# ═══════════════════════════════════════════════════════════════════════════════56# Basic Information7name: excel-automation8description: ">"9version: "1.0"10author: claude-office-skills11license: MIT1213# Categorization14category: spreadsheet15tags:16- excel17- automation18- macro19- workflow20department: All2122# AI Model Compatibility23models:24recommended:25- claude-sonnet-426- claude-opus-427compatible:28- claude-3-5-sonnet29- gpt-430- gpt-4o3132# MCP Tools Integration33mcp:34server: office-mcp35tools:36- read_xlsx37- create_xlsx38- apply_formula39- pivot_table4041# Skill Capabilities42capabilities:43- automation44- data_processing45- reporting4647# Language Support48languages:49- en50- zh51---5253# Excel Automation Skill5455## Overview5657This skill enables advanced Excel automation using **xlwings** - a library that can interact with live Excel instances. Unlike openpyxl (file-only), xlwings can control Excel in real-time, execute VBA, update dashboards, and automate complex workflows.5859## How to Use60611. Describe the Excel automation task you need622. Specify if you need live Excel interaction or file processing633. I'll generate xlwings code and execute it6465**Example prompts:**66- "Update this live Excel dashboard with new data"67- "Run this VBA macro and get the results"68- "Create an Excel add-in for data validation"69- "Automate monthly report generation with live charts"7071## Domain Knowledge7273### xlwings vs openpyxl7475| Feature | xlwings | openpyxl |76|---------|---------|----------|77| Requires Excel | Yes | No |78| Live interaction | Yes | No |79| VBA execution | Yes | No |80| Speed (large files) | Fast | Slow |81| Server deployment | Limited | Easy |8283### xlwings Fundamentals8485```python86import xlwings as xw8788# Connect to active Excel workbook89wb = xw.Book.caller() # From Excel add-in90wb = xw.books.active # Active workbook9192# Open specific file93wb = xw.Book('path/to/file.xlsx')9495# Create new workbook96wb = xw.Book()9798# Get sheet99sheet = wb.sheets['Sheet1']100sheet = wb.sheets[0]101```102103### Working with Ranges104105#### Reading and Writing106```python107# Single cell108sheet['A1'].value = 'Hello'109value = sheet['A1'].value110111# Range112sheet['A1:C3'].value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]113data = sheet['A1:C3'].value # Returns list of lists114115# Named range116sheet['MyRange'].value = 'Named data'117118# Expand range (detect data boundaries)119sheet['A1'].expand().value # All connected data120sheet['A1'].expand('table').value # Table format121```122123#### Dynamic Ranges124```python125# Current region (like Ctrl+Shift+End)126data = sheet['A1'].current_region.value127128# Used range129used = sheet.used_range.value130131# Last row with data132last_row = sheet['A1'].end('down').row133134# Resize range135rng = sheet['A1'].resize(10, 5) # 10 rows, 5 columns136```137138### Formatting139```python140# Font141sheet['A1'].font.bold = True142sheet['A1'].font.size = 14143sheet['A1'].font.color = (255, 0, 0) # RGB red144145# Fill146sheet['A1'].color = (255, 255, 0) # Yellow background147148# Number format149sheet['B1'].number_format = '$#,##0.00'150151# Column width152sheet['A:A'].column_width = 20153154# Row height155sheet['1:1'].row_height = 30156157# Autofit158sheet['A:D'].autofit()159```160161### Excel Features162163#### Charts164```python165# Add chart166chart = sheet.charts.add(left=100, top=100, width=400, height=250)167chart.set_source_data(sheet['A1:B10'])168chart.chart_type = 'column_clustered'169chart.name = 'Sales Chart'170171# Modify existing chart172chart = sheet.charts['Sales Chart']173chart.chart_type = 'line'174```175176#### Tables177```python178# Create Excel Table179rng = sheet['A1'].expand()180table = sheet.tables.add(source=rng, name='SalesTable')181182# Refresh table183table.refresh()184185# Access table data186table_data = table.data_body_range.value187```188189#### Pictures190```python191# Add picture192sheet.pictures.add('logo.png', left=10, top=10, width=100, height=50)193194# Update picture from matplotlib195import matplotlib.pyplot as plt196fig, ax = plt.subplots()197ax.plot([1, 2, 3], [1, 4, 9])198sheet.pictures.add(fig, name='MyPlot', update=True)199```200201### VBA Integration202```python203# Run VBA macro204wb.macro('MacroName')()205206# With arguments207wb.macro('MyMacro')('arg1', 'arg2')208209# Get return value210result = wb.macro('CalculateTotal')(100, 200)211212# Access VBA module213vb_code = wb.api.VBProject.VBComponents('Module1').CodeModule.Lines(1, 10)214```215216### User Defined Functions (UDFs)217```python218# Define a UDF (in Python file)219import xlwings as xw220221@xw.func222def my_sum(x, y):223"""Add two numbers"""224return x + y225226@xw.func227@xw.arg('data', ndim=2)228def my_array_func(data):229"""Process array data"""230import numpy as np231return np.sum(data)232233# These become Excel functions: =my_sum(A1, B1)234```235236### Application Control237```python238# Excel application settings239app = xw.apps.active240app.screen_updating = False # Speed up241app.calculation = 'manual' # Manual calc242app.display_alerts = False # Suppress dialogs243244# Perform operations...245246# Restore247app.screen_updating = True248app.calculation = 'automatic'249app.display_alerts = True250```251252## Best Practices2532541. **Disable Screen Updating**: For batch operations2552. **Use Arrays**: Read/write entire ranges, not cell-by-cell2563. **Manual Calculation**: Turn off auto-calc during data loading2574. **Close Connections**: Properly close workbooks when done2585. **Error Handling**: Handle Excel not being installed259260## Common Patterns261262### Performance Optimization263```python264import xlwings as xw265266def batch_update(data, workbook_path):267app = xw.App(visible=False)268try:269app.screen_updating = False270app.calculation = 'manual'271272wb = app.books.open(workbook_path)273sheet = wb.sheets['Data']274275# Write all data at once276sheet['A1'].value = data277278app.calculation = 'automatic'279wb.save()280finally:281wb.close()282app.quit()283```284285### Dashboard Update286```python287def update_dashboard(data_dict):288wb = xw.books.active289290# Update data sheet291data_sheet = wb.sheets['Data']292for name, values in data_dict.items():293data_sheet[name].value = values294295# Refresh all charts296dashboard = wb.sheets['Dashboard']297for chart in dashboard.charts:298chart.refresh()299300# Update timestamp301from datetime import datetime302dashboard['A1'].value = f'Last Updated: {datetime.now()}'303```304305### Report Generator306```python307def generate_monthly_report(month, data):308template = xw.Book('template.xlsx')309310# Fill data311sheet = template.sheets['Report']312sheet['B2'].value = month313sheet['A5'].value = data314315# Run calculations316template.app.calculate()317318# Export to PDF319sheet.api.ExportAsFixedFormat(0, f'report_{month}.pdf')320321template.save(f'report_{month}.xlsx')322```323324## Examples325326### Example 1: Live Dashboard Update327```python328import xlwings as xw329import pandas as pd330from datetime import datetime331332# Connect to running Excel333wb = xw.books.active334dashboard = wb.sheets['Dashboard']335data_sheet = wb.sheets['Data']336337# Fetch new data (simulated)338new_data = pd.DataFrame({339'Date': pd.date_range('2024-01-01', periods=30),340'Sales': [1000 + i*50 for i in range(30)],341'Costs': [600 + i*30 for i in range(30)]342})343344# Update data sheet345data_sheet['A1'].value = new_data346347# Calculate profit348data_sheet['D1'].value = 'Profit'349data_sheet['D2'].value = '=B2-C2'350data_sheet['D2'].expand('down').value = data_sheet['D2'].formula351352# Update KPIs on dashboard353dashboard['B2'].value = new_data['Sales'].sum()354dashboard['B3'].value = new_data['Costs'].sum()355dashboard['B4'].value = new_data['Sales'].sum() - new_data['Costs'].sum()356dashboard['A1'].value = f'Updated: {datetime.now().strftime("%Y-%m-%d %H:%M")}'357358# Refresh charts359for chart in dashboard.charts:360chart.api.Refresh()361362print("Dashboard updated!")363```364365### Example 2: Batch Processing Multiple Files366```python367import xlwings as xw368from pathlib import Path369370def process_sales_files(folder_path, output_path):371"""Consolidate multiple Excel files into one summary."""372373app = xw.App(visible=False)374app.screen_updating = False375376try:377# Create summary workbook378summary_wb = xw.Book()379summary_sheet = summary_wb.sheets[0]380summary_sheet.name = 'Consolidated'381382headers = ['File', 'Total Sales', 'Total Units', 'Avg Price']383summary_sheet['A1'].value = headers384385row = 2386for file in Path(folder_path).glob('*.xlsx'):387wb = app.books.open(str(file))388data_sheet = wb.sheets['Sales']389390# Extract summary391total_sales = data_sheet['B:B'].api.SpecialCells(11).Value # xlCellTypeConstants392total_units = data_sheet['C:C'].api.SpecialCells(11).Value393394# Calculate and write395summary_sheet[f'A{row}'].value = file.name396summary_sheet[f'B{row}'].value = sum(total_sales) if isinstance(total_sales, (list, tuple)) else total_sales397summary_sheet[f'C{row}'].value = sum(total_units) if isinstance(total_units, (list, tuple)) else total_units398summary_sheet[f'D{row}'].value = f'=B{row}/C{row}'399400wb.close()401row += 1402403# Format summary404summary_sheet['A1:D1'].font.bold = True405summary_sheet['B:D'].number_format = '$#,##0.00'406summary_sheet['A:D'].autofit()407408summary_wb.save(output_path)409410finally:411app.quit()412413print(f"Consolidated {row-2} files to {output_path}")414415# Usage416process_sales_files('/path/to/sales/', 'consolidated_sales.xlsx')417```418419### Example 3: Excel Add-in with UDFs420```python421# myudfs.py - Place in xlwings project422423import xlwings as xw424import numpy as np425426@xw.func427@xw.arg('data', pd.DataFrame, index=False, header=False)428@xw.ret(expand='table')429def GROWTH_RATE(data):430"""Calculate period-over-period growth rate"""431values = data.iloc[:, 0].values432growth = np.diff(values) / values[:-1] * 100433return [['Growth %']] + [[g] for g in growth]434435@xw.func436@xw.arg('range1', np.array, ndim=2)437@xw.arg('range2', np.array, ndim=2)438def CORRELATION(range1, range2):439"""Calculate correlation between two ranges"""440return np.corrcoef(range1.flatten(), range2.flatten())[0, 1]441442@xw.func443def SENTIMENT(text):444"""Basic sentiment analysis (placeholder)"""445positive = ['good', 'great', 'excellent', 'amazing']446negative = ['bad', 'poor', 'terrible', 'awful']447448text_lower = text.lower()449pos_count = sum(word in text_lower for word in positive)450neg_count = sum(word in text_lower for word in negative)451452if pos_count > neg_count:453return 'Positive'454elif neg_count > pos_count:455return 'Negative'456return 'Neutral'457```458459## Limitations460461- Requires Excel to be installed462- Limited support on macOS for some features463- Not suitable for server-side processing464- VBA features require trust settings465- Performance varies with Excel version466467## Installation468469```bash470pip install xlwings471472# For add-in functionality473xlwings addin install474```475476## Resources477478- [xlwings Documentation](https://docs.xlwings.org/)479- [GitHub Repository](https://github.com/xlwings/xlwings)480- [UDF Tutorial](https://docs.xlwings.org/en/stable/udfs.html)481- [Excel VBA Reference](https://docs.microsoft.com/en-us/office/vba/api/overview/excel)482