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 or Excel Required for Formula Recalculation: Use a spreadsheet engine (e.g., LibreOffice headless or Excel) to recalc formulas and update cached values.
Reading and analyzing data
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): Recalc with a spreadsheet engine (e.g., LibreOffice headless or Excel) to refresh cached values.
- Verify and fix any errors:
- Check for error values (#REF!, #DIV/0!, #VALUE!, #NAME?) after recalculation
- 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. Recalculate formulas by opening the workbook in a spreadsheet engine (e.g., LibreOffice headless or Excel) and saving it so cached values update. Scan for Excel errors (#REF!, #DIV/0!, etc.) after recalculation and fix any invalid references or data types.
Formula Verification Checklist
Quick checks to ensure formulas work correctly:
Essential Verification
Common Pitfalls
Formula Testing Strategy
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 - recalc with a spreadsheet engine 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: xlsx3description: 'Comprehensive spreadsheet creation, editing, and analysis with support4 for formulas, formatting, data analysis, and visualization. When Claude needs to5 work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets6 with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing7 spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets,8 or (5) Recalculating formulas'9license: Proprietary. LICENSE.txt has complete terms10---1112# Requirements for Outputs1314## All Excel files1516### Zero Formula Errors17- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1819### Preserve Existing Templates (when updating templates)20- Study and EXACTLY match existing format, style, and conventions when modifying files21- Never impose standardized formatting on files with established patterns22- Existing template conventions ALWAYS override these guidelines2324## Financial models2526### Color Coding Standards27Unless otherwise stated by the user or existing template2829#### Industry-Standard Color Conventions30- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios31- **Black text (RGB: 0,0,0)**: ALL formulas and calculations32- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook33- **Red text (RGB: 255,0,0)**: External links to other files34- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated3536### Number Formatting Standards3738#### Required Format Rules39- **Years**: Format as text strings (e.g., "2024" not "2,024")40- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")41- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")42- **Percentages**: Default to 0.0% format (one decimal)43- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)44- **Negative numbers**: Use parentheses (123) not minus -1234546### Formula Construction Rules4748#### Assumptions Placement49- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells50- Use cell references instead of hardcoded values in formulas51- Example: Use =B5*(1+$B$6) instead of =B5*1.055253#### Formula Error Prevention54- Verify all cell references are correct55- Check for off-by-one errors in ranges56- Ensure consistent formulas across all projection periods57- Test with edge cases (zero values, negative numbers)58- Verify no unintended circular references5960#### Documentation Requirements for Hardcodes61- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"62- Examples:63 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"64 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"65 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"66 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"6768# XLSX creation, editing, and analysis6970## Overview7172A 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.7374## Important Requirements7576**LibreOffice or Excel Required for Formula Recalculation**: Use a spreadsheet engine (e.g., LibreOffice headless or Excel) to recalc formulas and update cached values.7778## Reading and analyzing data7980### Data analysis with pandas81For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:8283```python84import pandas as pd8586# Read Excel87df = pd.read_excel('file.xlsx') # Default: first sheet88all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict8990# Analyze91df.head() # Preview data92df.info() # Column info93df.describe() # Statistics9495# Write Excel96df.to_excel('output.xlsx', index=False)97```9899## Excel File Workflows100101## CRITICAL: Use Formulas, Not Hardcoded Values102103**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.104105### ❌ WRONG - Hardcoding Calculated Values106```python107# Bad: Calculating in Python and hardcoding result108total = df['Sales'].sum()109sheet['B10'] = total # Hardcodes 5000110111# Bad: Computing growth rate in Python112growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']113sheet['C5'] = growth # Hardcodes 0.15114115# Bad: Python calculation for average116avg = sum(values) / len(values)117sheet['D20'] = avg # Hardcodes 42.5118```119120### ✅ CORRECT - Using Excel Formulas121```python122# Good: Let Excel calculate the sum123sheet['B10'] = '=SUM(B2:B9)'124125# Good: Growth rate as Excel formula126sheet['C5'] = '=(C4-C2)/C2'127128# Good: Average using Excel function129sheet['D20'] = '=AVERAGE(D2:D19)'130```131132This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.133134## Common Workflow1351. **Choose tool**: pandas for data, openpyxl for formulas/formatting1362. **Create/Load**: Create new workbook or load existing file1373. **Modify**: Add/edit data, formulas, and formatting1384. **Save**: Write to file1395. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Recalc with a spreadsheet engine (e.g., LibreOffice headless or Excel) to refresh cached values.1406. **Verify and fix any errors**: 141 - Check for error values (#REF!, #DIV/0!, #VALUE!, #NAME?) after recalculation142 - Fix the identified errors and recalculate again143 - Common errors to fix:144 - `#REF!`: Invalid cell references145 - `#DIV/0!`: Division by zero146 - `#VALUE!`: Wrong data type in formula147 - `#NAME?`: Unrecognized formula name148149### Creating new Excel files150151```python152# Using openpyxl for formulas and formatting153from openpyxl import Workbook154from openpyxl.styles import Font, PatternFill, Alignment155156wb = Workbook()157sheet = wb.active158159# Add data160sheet['A1'] = 'Hello'161sheet['B1'] = 'World'162sheet.append(['Row', 'of', 'data'])163164# Add formula165sheet['B2'] = '=SUM(A1:A10)'166167# Formatting168sheet['A1'].font = Font(bold=True, color='FF0000')169sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')170sheet['A1'].alignment = Alignment(horizontal='center')171172# Column width173sheet.column_dimensions['A'].width = 20174175wb.save('output.xlsx')176```177178### Editing existing Excel files179180```python181# Using openpyxl to preserve formulas and formatting182from openpyxl import load_workbook183184# Load existing file185wb = load_workbook('existing.xlsx')186sheet = wb.active # or wb['SheetName'] for specific sheet187188# Working with multiple sheets189for sheet_name in wb.sheetnames:190 sheet = wb[sheet_name]191 print(f"Sheet: {sheet_name}")192193# Modify cells194sheet['A1'] = 'New Value'195sheet.insert_rows(2) # Insert row at position 2196sheet.delete_cols(3) # Delete column 3197198# Add new sheet199new_sheet = wb.create_sheet('NewSheet')200new_sheet['A1'] = 'Data'201202wb.save('modified.xlsx')203```204205## Recalculating formulas206207Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Recalculate formulas by opening the workbook in a spreadsheet engine (e.g., LibreOffice headless or Excel) and saving it so cached values update. Scan for Excel errors (#REF!, #DIV/0!, etc.) after recalculation and fix any invalid references or data types.208209## Formula Verification Checklist210211Quick checks to ensure formulas work correctly:212213### Essential Verification214- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model215- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)216- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)217218### Common Pitfalls219- [ ] **NaN handling**: Check for null values with `pd.notna()`220- [ ] **Far-right columns**: FY data often in columns 50+ 221- [ ] **Multiple matches**: Search all occurrences, not just first222- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)223- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)224- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets225226### Formula Testing Strategy227- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly228- [ ] **Verify dependencies**: Check all cells referenced in formulas exist229- [ ] **Test edge cases**: Include zero, negative, and very large values230231## Best Practices232233### Library Selection234- **pandas**: Best for data analysis, bulk operations, and simple data export235- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features236237### Working with openpyxl238- Cell indices are 1-based (row=1, column=1 refers to cell A1)239- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`240- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost241- For large files: Use `read_only=True` for reading or `write_only=True` for writing242- Formulas are preserved but not evaluated - recalc with a spreadsheet engine to update values243244### Working with pandas245- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`246- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`247- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`248249## Code Style Guidelines250**IMPORTANT**: When generating Python code for Excel operations:251- Write minimal, concise Python code without unnecessary comments252- Avoid verbose variable names and redundant operations253- Avoid unnecessary print statements254255**For Excel files themselves**:256- Add comments to cells with complex formulas or important assumptions257- Document data sources for hardcoded values258- Include notes for key calculations and model sections