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: If you create or modify formulas, use LibreOffice in headless mode to open, recalculate, and save the workbook before returning it.
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): Use LibreOffice headless mode to open and save the workbook.
libreoffice --headless --convert-to xlsx --outdir . output.xlsx
- Verify and fix any errors:
- Reopen the workbook and inspect formula/error cells.
- Fix invalid references, divide-by-zero errors, missing inputs, and other formula errors.
- Recalculate again after each fix.
- 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 LibreOffice headless mode to recalculate formulas:
libreoffice --headless --convert-to xlsx --outdir . <excel_file>
Example:
libreoffice --headless --convert-to xlsx --outdir . output.xlsx
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 recalculation results
LibreOffice does not return structured formula diagnostics. Reopen the workbook
with data_only=True or inspect known formula cells to confirm values were
calculated and no Excel error values remain.
{
"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 LibreOffice headless recalculation workflow 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-23description: 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 formulas4license: Proprietary. LICENSE.txt has complete terms5---67# Requirements for Outputs89## All Excel files1011### Zero Formula Errors1213- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1415### Preserve Existing Templates (when updating templates)1617- 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 Standards2425Unless otherwise stated by the user or existing template2627#### Industry-Standard Color Conventions2829- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios30- **Black text (RGB: 0,0,0)**: ALL formulas and calculations31- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook32- **Red text (RGB: 255,0,0)**: External links to other files33- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated3435### Number Formatting Standards3637#### Required Format Rules3839- **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 Placement4950- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells51- Use cell references instead of hardcoded values in formulas52- Example: Use =B5*(1+$B$6) instead of =B5*1.055354#### Formula Error Prevention5556- Verify all cell references are correct57- Check for off-by-one errors in ranges58- Ensure consistent formulas across all projection periods59- Test with edge cases (zero values, negative numbers)60- Verify no unintended circular references6162#### Documentation Requirements for Hardcodes6364- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"65- Examples:66 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"67 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"68 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"69 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"7071# XLSX creation, editing, and analysis7273## Overview7475A 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.7677## Important Requirements7879**LibreOffice Required for Formula Recalculation**: If you create or modify formulas, use LibreOffice in headless mode to open, recalculate, and save the workbook before returning it.8081## Reading and analyzing data8283### Data analysis with pandas8485For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:8687```python88import pandas as pd8990# Read Excel91df = pd.read_excel('file.xlsx') # Default: first sheet92all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict9394# Analyze95df.head() # Preview data96df.info() # Column info97df.describe() # Statistics9899# Write Excel100df.to_excel('output.xlsx', index=False)101```102103## Excel File Workflows104105## CRITICAL: Use Formulas, Not Hardcoded Values106107**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.108109### ❌ WRONG - Hardcoding Calculated Values110111```python112# Bad: Calculating in Python and hardcoding result113total = df['Sales'].sum()114sheet['B10'] = total # Hardcodes 5000115116# Bad: Computing growth rate in Python117growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']118sheet['C5'] = growth # Hardcodes 0.15119120# Bad: Python calculation for average121avg = sum(values) / len(values)122sheet['D20'] = avg # Hardcodes 42.5123```124125### ✅ CORRECT - Using Excel Formulas126127```python128# Good: Let Excel calculate the sum129sheet['B10'] = '=SUM(B2:B9)'130131# Good: Growth rate as Excel formula132sheet['C5'] = '=(C4-C2)/C2'133134# Good: Average using Excel function135sheet['D20'] = '=AVERAGE(D2:D19)'136```137138This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.139140## Common Workflow1411421. **Choose tool**: pandas for data, openpyxl for formulas/formatting1432. **Create/Load**: Create new workbook or load existing file1443. **Modify**: Add/edit data, formulas, and formatting1454. **Save**: Write to file1465. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use LibreOffice headless mode to open and save the workbook.147 ```bash148 libreoffice --headless --convert-to xlsx --outdir . output.xlsx149 ```1506. **Verify and fix any errors**:151 - Reopen the workbook and inspect formula/error cells.152 - Fix invalid references, divide-by-zero errors, missing inputs, and other formula errors.153 - Recalculate again after each fix.154 - Common errors to fix:155 - `#REF!`: Invalid cell references156 - `#DIV/0!`: Division by zero157 - `#VALUE!`: Wrong data type in formula158 - `#NAME?`: Unrecognized formula name159160### Creating new Excel files161162```python163# Using openpyxl for formulas and formatting164from openpyxl import Workbook165from openpyxl.styles import Font, PatternFill, Alignment166167wb = Workbook()168sheet = wb.active169170# Add data171sheet['A1'] = 'Hello'172sheet['B1'] = 'World'173sheet.append(['Row', 'of', 'data'])174175# Add formula176sheet['B2'] = '=SUM(A1:A10)'177178# Formatting179sheet['A1'].font = Font(bold=True, color='FF0000')180sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')181sheet['A1'].alignment = Alignment(horizontal='center')182183# Column width184sheet.column_dimensions['A'].width = 20185186wb.save('output.xlsx')187```188189### Editing existing Excel files190191```python192# Using openpyxl to preserve formulas and formatting193from openpyxl import load_workbook194195# Load existing file196wb = load_workbook('existing.xlsx')197sheet = wb.active # or wb['SheetName'] for specific sheet198199# Working with multiple sheets200for sheet_name in wb.sheetnames:201 sheet = wb[sheet_name]202 print(f"Sheet: {sheet_name}")203204# Modify cells205sheet['A1'] = 'New Value'206sheet.insert_rows(2) # Insert row at position 2207sheet.delete_cols(3) # Delete column 3208209# Add new sheet210new_sheet = wb.create_sheet('NewSheet')211new_sheet['A1'] = 'Data'212213wb.save('modified.xlsx')214```215216## Recalculating formulas217218Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use LibreOffice headless mode to recalculate formulas:219220```bash221libreoffice --headless --convert-to xlsx --outdir . <excel_file>222```223224Example:225226```bash227libreoffice --headless --convert-to xlsx --outdir . output.xlsx228```229230The script:231232- Automatically sets up LibreOffice macro on first run233- Recalculates all formulas in all sheets234- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)235- Returns JSON with detailed error locations and counts236- Works on both Linux and macOS237238## Formula Verification Checklist239240Quick checks to ensure formulas work correctly:241242### Essential Verification243244- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model245- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)246- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)247248### Common Pitfalls249250- [ ] **NaN handling**: Check for null values with `pd.notna()`251- [ ] **Far-right columns**: FY data often in columns 50+252- [ ] **Multiple matches**: Search all occurrences, not just first253- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)254- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)255- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets256257### Formula Testing Strategy258259- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly260- [ ] **Verify dependencies**: Check all cells referenced in formulas exist261- [ ] **Test edge cases**: Include zero, negative, and very large values262263### Interpreting recalculation results264265LibreOffice does not return structured formula diagnostics. Reopen the workbook266with `data_only=True` or inspect known formula cells to confirm values were267calculated and no Excel error values remain.268269```json270{271 "status": "success", // or "errors_found"272 "total_errors": 0, // Total error count273 "total_formulas": 42, // Number of formulas in file274 "error_summary": {275 // Only present if errors found276 "#REF!": {277 "count": 2,278 "locations": ["Sheet1!B5", "Sheet1!C10"]279 }280 }281}282```283284## Best Practices285286### Library Selection287288- **pandas**: Best for data analysis, bulk operations, and simple data export289- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features290291### Working with openpyxl292293- Cell indices are 1-based (row=1, column=1 refers to cell A1)294- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`295- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost296- For large files: Use `read_only=True` for reading or `write_only=True` for writing297- Formulas are preserved but not evaluated - use LibreOffice headless recalculation workflow to update values298299### Working with pandas300301- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`302- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`303- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`304305## Code Style Guidelines306307**IMPORTANT**: When generating Python code for Excel operations:308309- Write minimal, concise Python code without unnecessary comments310- Avoid verbose variable names and redundant operations311- Avoid unnecessary print statements312313**For Excel files themselves**:314315- Add comments to cells with complex formulas or important assumptions316- Document data sources for hardcoded values317- Include notes for key calculations and model sections