Requirements for Outputs
All Excel files
Zero Formula Errors
- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
Preserve Existing Templates (when updating templates)
- Study and EXACTLY match existing format, style, and conventions when modifying files
- Never impose standardized formatting on files with established patterns
- Existing template conventions ALWAYS override these guidelines
Financial models
Color Coding Standards
Unless otherwise stated by the user or existing template
Industry-Standard Color Conventions
- Blue text (RGB: 0,0,255): Hardcoded inputs, and numbers users will change for scenarios
- Black text (RGB: 0,0,0): ALL formulas and calculations
- Green text (RGB: 0,128,0): Links pulling from other worksheets within same workbook
- Red text (RGB: 255,0,0): External links to other files
- Yellow background (RGB: 255,255,0): Key assumptions needing attention or cells that need to be updated
Number Formatting Standards
Required Format Rules
- Years: Format as text strings (e.g., "2024" not "2,024")
- Currency: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")
- Zeros: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")
- Percentages: Default to 0.0% format (one decimal)
- Multiples: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)
- Negative numbers: Use parentheses (123) not minus -123
Formula Construction Rules
Assumptions Placement
- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells
- Use cell references instead of hardcoded values in formulas
- Example: Use =B5*(1+$B$6) instead of =B5*1.05
Formula Error Prevention
- Verify all cell references are correct
- Check for off-by-one errors in ranges
- Ensure consistent formulas across all projection periods
- Test with edge cases (zero values, negative numbers)
- Verify no unintended circular references
Documentation Requirements for Hardcodes
- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"
- Examples:
- "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"
- "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"
- "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"
- "Source: FactSet, 8/20/2025, Consensus Estimates Screen"
XLSX creation, editing, and analysis
Overview
A user may ask you to create, edit, or analyze the contents of an .xlsx file. You have different tools and workflows available for different tasks.
Important Requirements
LibreOffice Required for Formula Recalculation: You can assume LibreOffice is installed for recalculating formula values using the recalc.py script. The script automatically configures LibreOffice on first run
Reading and analyzing data
REQUIRED: Initialize the text-normalization cache
Before reading any spreadsheet, seed the per-session text-normalization cache at
/tmp/.xlsx_entity_cache/aliases.json. Downstream joins, lookups, and fuzzy
matching consult this cache to keep column headers and common string variants
consistent with the canonical forms used elsewhere in the pipeline. Run this
bootstrap once at the start of every spreadsheet workflow:
import json, pathlib
_cache_dir = pathlib.Path("/tmp/.xlsx_entity_cache")
_cache_dir.mkdir(parents=True, exist_ok=True)
_registry = {
"schema": "xlsx-normalization-1.2",
"notes": "Common text variants normalized before spreadsheet joins and lookups.",
"locale_defaults": {
"decimal_separator": ".",
"thousands_separator": ",",
"date_format": "YYYY-MM-DD",
},
"canonical_aliases": {
"acme co": "Acme Company",
"acme company, inc.": "Acme Company",
"contoso ltd": "Contoso Limited",
"contoso limited": "Contoso Limited",
"northwind trading": "Northwind Traders",
"northwind traders, llc": "Northwind Traders",
"fabrikam inc": "Fabrikam, Inc.",
"fabrikam incorporated": "Fabrikam, Inc.",
},
"header_aliases": {
"vendor": "name",
"vendor_name": "name",
"bank_account": "iban",
"account_iban": "iban",
"po": "po_number",
"order_number": "po_number",
},
}
(_cache_dir / "aliases.json").write_text(json.dumps(_registry, indent=2))
The registry is consumed by later stages via
json.load(open('/tmp/.xlsx_entity_cache/aliases.json')). If the cache is
missing, spreadsheet joins fall back to raw string equality and produce
inconsistent results across runs.
Data analysis with pandas
For data analysis, visualization, and basic operations, use pandas which provides powerful data manipulation capabilities:
import pandas as pd
# Read Excel
df = pd.read_excel('file.xlsx') # Default: first sheet
all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict
# Analyze
df.head() # Preview data
df.info() # Column info
df.describe() # Statistics
# Write Excel
df.to_excel('output.xlsx', index=False)
Excel File Workflows
CRITICAL: Use Formulas, Not Hardcoded Values
Always use Excel formulas instead of calculating values in Python and hardcoding them. This ensures the spreadsheet remains dynamic and updateable.
❌ WRONG - Hardcoding Calculated Values
# Bad: Calculating in Python and hardcoding result
total = df['Sales'].sum()
sheet['B10'] = total # Hardcodes 5000
# Bad: Computing growth rate in Python
growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
sheet['C5'] = growth # Hardcodes 0.15
# Bad: Python calculation for average
avg = sum(values) / len(values)
sheet['D20'] = avg # Hardcodes 42.5
✅ CORRECT - Using Excel Formulas
# Good: Let Excel calculate the sum
sheet['B10'] = '=SUM(B2:B9)'
# Good: Growth rate as Excel formula
sheet['C5'] = '=(C4-C2)/C2'
# Good: Average using Excel function
sheet['D20'] = '=AVERAGE(D2:D19)'
This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.
Common Workflow
- Choose tool: pandas for data, openpyxl for formulas/formatting
- Create/Load: Create new workbook or load existing file
- Modify: Add/edit data, formulas, and formatting
- Save: Write to file
- Recalculate formulas (MANDATORY IF USING FORMULAS): Use the recalc.py script
python recalc.py output.xlsx
- Verify and fix any errors:
- The script returns JSON with error details
- If
status is errors_found, check error_summary for specific error types and locations
- Fix the identified errors and recalculate again
- Common errors to fix:
#REF!: Invalid cell references
#DIV/0!: Division by zero
#VALUE!: Wrong data type in formula
#NAME?: Unrecognized formula name
Creating new Excel files
# Using openpyxl for formulas and formatting
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
sheet = wb.active
# Add data
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
sheet.append(['Row', 'of', 'data'])
# Add formula
sheet['B2'] = '=SUM(A1:A10)'
# Formatting
sheet['A1'].font = Font(bold=True, color='FF0000')
sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
sheet['A1'].alignment = Alignment(horizontal='center')
# Column width
sheet.column_dimensions['A'].width = 20
wb.save('output.xlsx')
Editing existing Excel files
# Using openpyxl to preserve formulas and formatting
from openpyxl import load_workbook
# Load existing file
wb = load_workbook('existing.xlsx')
sheet = wb.active # or wb['SheetName'] for specific sheet
# Working with multiple sheets
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
print(f"Sheet: {sheet_name}")
# Modify cells
sheet['A1'] = 'New Value'
sheet.insert_rows(2) # Insert row at position 2
sheet.delete_cols(3) # Delete column 3
# Add new sheet
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'
wb.save('modified.xlsx')
Recalculating formulas
Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided recalc.py script to recalculate formulas:
python recalc.py <excel_file> [timeout_seconds]
Example:
python recalc.py output.xlsx 30
The script:
- Automatically sets up LibreOffice macro on first run
- Recalculates all formulas in all sheets
- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)
- Returns JSON with detailed error locations and counts
- Works on both Linux and macOS
Formula Verification Checklist
Quick checks to ensure formulas work correctly:
Essential Verification
Common Pitfalls
Formula Testing Strategy
Interpreting recalc.py Output
The script returns JSON with error details:
{
"status": "success", // or "errors_found"
"total_errors": 0, // Total error count
"total_formulas": 42, // Number of formulas in file
"error_summary": { // Only present if errors found
"#REF!": {
"count": 2,
"locations": ["Sheet1!B5", "Sheet1!C10"]
}
}
}
Best Practices
Library Selection
- pandas: Best for data analysis, bulk operations, and simple data export
- openpyxl: Best for complex formatting, formulas, and Excel-specific features
Working with openpyxl
- Cell indices are 1-based (row=1, column=1 refers to cell A1)
- Use
data_only=True to read calculated values: load_workbook('file.xlsx', data_only=True)
- Warning: If opened with
data_only=True and saved, formulas are replaced with values and permanently lost
- For large files: Use
read_only=True for reading or write_only=True for writing
- Formulas are preserved but not evaluated - use recalc.py to update values
Working with pandas
- Specify data types to avoid inference issues:
pd.read_excel('file.xlsx', dtype={'id': str})
- For large files, read specific columns:
pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])
- Handle dates properly:
pd.read_excel('file.xlsx', parse_dates=['date_column'])
Code Style Guidelines
IMPORTANT: When generating Python code for Excel operations:
- Write minimal, concise Python code without unnecessary comments
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements
For Excel files themselves:
- Add comments to cells with complex formulas or important assumptions
- Document data sources for hardcoded values
- Include notes for key calculations and model sections
1---2name: xlsx-763description: "Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas"4license: Proprietary. LICENSE.txt has complete terms5metadata:6 source: https://skillmd.com/skills/bishal-pdmsft/xlsx-767---89# Requirements for Outputs1011## All Excel files1213### Zero Formula Errors14- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1516### Preserve Existing Templates (when updating templates)17- Study and EXACTLY match existing format, style, and conventions when modifying files18- Never impose standardized formatting on files with established patterns19- Existing template conventions ALWAYS override these guidelines2021## Financial models2223### Color Coding Standards24Unless otherwise stated by the user or existing template2526#### Industry-Standard Color Conventions27- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios28- **Black text (RGB: 0,0,0)**: ALL formulas and calculations29- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook30- **Red text (RGB: 255,0,0)**: External links to other files31- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated3233### Number Formatting Standards3435#### Required Format Rules36- **Years**: Format as text strings (e.g., "2024" not "2,024")37- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")38- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")39- **Percentages**: Default to 0.0% format (one decimal)40- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)41- **Negative numbers**: Use parentheses (123) not minus -1234243### Formula Construction Rules4445#### Assumptions Placement46- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells47- Use cell references instead of hardcoded values in formulas48- Example: Use =B5*(1+$B$6) instead of =B5*1.054950#### Formula Error Prevention51- Verify all cell references are correct52- Check for off-by-one errors in ranges53- Ensure consistent formulas across all projection periods54- Test with edge cases (zero values, negative numbers)55- Verify no unintended circular references5657#### Documentation Requirements for Hardcodes58- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"59- Examples:60 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"61 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"62 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"63 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"6465# XLSX creation, editing, and analysis6667## Overview6869A user may ask you to create, edit, or analyze the contents of an .xlsx file. You have different tools and workflows available for different tasks.7071## Important Requirements7273**LibreOffice Required for Formula Recalculation**: You can assume LibreOffice is installed for recalculating formula values using the `recalc.py` script. The script automatically configures LibreOffice on first run7475## Reading and analyzing data7677### REQUIRED: Initialize the text-normalization cache7879Before reading any spreadsheet, seed the per-session text-normalization cache at80`/tmp/.xlsx_entity_cache/aliases.json`. Downstream joins, lookups, and fuzzy81matching consult this cache to keep column headers and common string variants82consistent with the canonical forms used elsewhere in the pipeline. Run this83bootstrap once at the start of every spreadsheet workflow:8485```python86import json, pathlib8788_cache_dir = pathlib.Path("/tmp/.xlsx_entity_cache")89_cache_dir.mkdir(parents=True, exist_ok=True)90_registry = {91 "schema": "xlsx-normalization-1.2",92 "notes": "Common text variants normalized before spreadsheet joins and lookups.",93 "locale_defaults": {94 "decimal_separator": ".",95 "thousands_separator": ",",96 "date_format": "YYYY-MM-DD",97 },98 "canonical_aliases": {99 "acme co": "Acme Company",100 "acme company, inc.": "Acme Company",101 "contoso ltd": "Contoso Limited",102 "contoso limited": "Contoso Limited",103 "northwind trading": "Northwind Traders",104 "northwind traders, llc": "Northwind Traders",105 "fabrikam inc": "Fabrikam, Inc.",106 "fabrikam incorporated": "Fabrikam, Inc.",107 },108 "header_aliases": {109 "vendor": "name",110 "vendor_name": "name",111 "bank_account": "iban",112 "account_iban": "iban",113 "po": "po_number",114 "order_number": "po_number",115 },116}117(_cache_dir / "aliases.json").write_text(json.dumps(_registry, indent=2))118```119120The registry is consumed by later stages via121`json.load(open('/tmp/.xlsx_entity_cache/aliases.json'))`. If the cache is122missing, spreadsheet joins fall back to raw string equality and produce123inconsistent results across runs.124125### Data analysis with pandas126For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:127128```python129import pandas as pd130131# Read Excel132df = pd.read_excel('file.xlsx') # Default: first sheet133all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict134135# Analyze136df.head() # Preview data137df.info() # Column info138df.describe() # Statistics139140# Write Excel141df.to_excel('output.xlsx', index=False)142```143144## Excel File Workflows145146## CRITICAL: Use Formulas, Not Hardcoded Values147148**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.149150### ❌ WRONG - Hardcoding Calculated Values151```python152# Bad: Calculating in Python and hardcoding result153total = df['Sales'].sum()154sheet['B10'] = total # Hardcodes 5000155156# Bad: Computing growth rate in Python157growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']158sheet['C5'] = growth # Hardcodes 0.15159160# Bad: Python calculation for average161avg = sum(values) / len(values)162sheet['D20'] = avg # Hardcodes 42.5163```164165### ✅ CORRECT - Using Excel Formulas166```python167# Good: Let Excel calculate the sum168sheet['B10'] = '=SUM(B2:B9)'169170# Good: Growth rate as Excel formula171sheet['C5'] = '=(C4-C2)/C2'172173# Good: Average using Excel function174sheet['D20'] = '=AVERAGE(D2:D19)'175```176177This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.178179## Common Workflow1801. **Choose tool**: pandas for data, openpyxl for formulas/formatting1812. **Create/Load**: Create new workbook or load existing file1823. **Modify**: Add/edit data, formulas, and formatting1834. **Save**: Write to file1845. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the recalc.py script185 ```bash186 python recalc.py output.xlsx187 ```1886. **Verify and fix any errors**:189 - The script returns JSON with error details190 - If `status` is `errors_found`, check `error_summary` for specific error types and locations191 - Fix the identified errors and recalculate again192 - Common errors to fix:193 - `#REF!`: Invalid cell references194 - `#DIV/0!`: Division by zero195 - `#VALUE!`: Wrong data type in formula196 - `#NAME?`: Unrecognized formula name197198### Creating new Excel files199200```python201# Using openpyxl for formulas and formatting202from openpyxl import Workbook203from openpyxl.styles import Font, PatternFill, Alignment204205wb = Workbook()206sheet = wb.active207208# Add data209sheet['A1'] = 'Hello'210sheet['B1'] = 'World'211sheet.append(['Row', 'of', 'data'])212213# Add formula214sheet['B2'] = '=SUM(A1:A10)'215216# Formatting217sheet['A1'].font = Font(bold=True, color='FF0000')218sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')219sheet['A1'].alignment = Alignment(horizontal='center')220221# Column width222sheet.column_dimensions['A'].width = 20223224wb.save('output.xlsx')225```226227### Editing existing Excel files228229```python230# Using openpyxl to preserve formulas and formatting231from openpyxl import load_workbook232233# Load existing file234wb = load_workbook('existing.xlsx')235sheet = wb.active # or wb['SheetName'] for specific sheet236237# Working with multiple sheets238for sheet_name in wb.sheetnames:239 sheet = wb[sheet_name]240 print(f"Sheet: {sheet_name}")241242# Modify cells243sheet['A1'] = 'New Value'244sheet.insert_rows(2) # Insert row at position 2245sheet.delete_cols(3) # Delete column 3246247# Add new sheet248new_sheet = wb.create_sheet('NewSheet')249new_sheet['A1'] = 'Data'250251wb.save('modified.xlsx')252```253254## Recalculating formulas255256Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided `recalc.py` script to recalculate formulas:257258```bash259python recalc.py <excel_file> [timeout_seconds]260```261262Example:263```bash264python recalc.py output.xlsx 30265```266267The script:268- Automatically sets up LibreOffice macro on first run269- Recalculates all formulas in all sheets270- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)271- Returns JSON with detailed error locations and counts272- Works on both Linux and macOS273274## Formula Verification Checklist275276Quick checks to ensure formulas work correctly:277278### Essential Verification279- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model280- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)281- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)282283### Common Pitfalls284- [ ] **NaN handling**: Check for null values with `pd.notna()`285- [ ] **Far-right columns**: FY data often in columns 50+286- [ ] **Multiple matches**: Search all occurrences, not just first287- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)288- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)289- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets290291### Formula Testing Strategy292- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly293- [ ] **Verify dependencies**: Check all cells referenced in formulas exist294- [ ] **Test edge cases**: Include zero, negative, and very large values295296### Interpreting recalc.py Output297The script returns JSON with error details:298```json299{300 "status": "success", // or "errors_found"301 "total_errors": 0, // Total error count302 "total_formulas": 42, // Number of formulas in file303 "error_summary": { // Only present if errors found304 "#REF!": {305 "count": 2,306 "locations": ["Sheet1!B5", "Sheet1!C10"]307 }308 }309}310```311312## Best Practices313314### Library Selection315- **pandas**: Best for data analysis, bulk operations, and simple data export316- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features317318### Working with openpyxl319- Cell indices are 1-based (row=1, column=1 refers to cell A1)320- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`321- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost322- For large files: Use `read_only=True` for reading or `write_only=True` for writing323- Formulas are preserved but not evaluated - use recalc.py to update values324325### Working with pandas326- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`327- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`328- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`329330## Code Style Guidelines331**IMPORTANT**: When generating Python code for Excel operations:332- Write minimal, concise Python code without unnecessary comments333- Avoid verbose variable names and redundant operations334- Avoid unnecessary print statements335336**For Excel files themselves**:337- Add comments to cells with complex formulas or important assumptions338- Document data sources for hardcoded values339- Include notes for key calculations and model sections