Requirements for Outputs
All Excel files
Professional Font
- Use a consistent, professional font (e.g., Arial, Times New Roman) for all
deliverables unless otherwise instructed by the user
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 scripts/recalc.py
script. The script automatically configures LibreOffice on first run, including
in sandboxed environments where Unix sockets are restricted (handled by
scripts/office/soffice.py)
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 the
scripts/recalc.py script
python scripts/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 scripts/recalc.py script to recalculate
formulas:
python scripts/recalc.py <excel_file> [timeout_seconds]
Example:
python scripts/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 scripts/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 scripts/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: xlsx3description: >-4 Use this skill any time a spreadsheet file is the primary input or output. This means5 any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm,6 .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting,7 cleaning messy data); create a new spreadsheet from scratch or from other data sources;8 or convert between tabular file formats. Trigger especially when the user references a9 spreadsheet file by name or path — even casually (like "the xlsx in my downloads") —10 and wants something done to it or produced from it. Also trigger for cleaning or11 restructuring messy tabular data files (malformed rows, misplaced headers, junk data)12 into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger13 when the primary deliverable is a Word document, HTML report, standalone Python script,14 database pipeline, or Google Sheets API integration, even if tabular data is involved.15license: Proprietary. LICENSE.txt has complete terms16---1718# Requirements for Outputs1920## All Excel files2122### Professional Font2324- Use a consistent, professional font (e.g., Arial, Times New Roman) for all25 deliverables unless otherwise instructed by the user2627### Zero Formula Errors2829- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!,30 #VALUE!, #N/A, #NAME?)3132### Preserve Existing Templates (when updating templates)3334- Study and EXACTLY match existing format, style, and conventions when modifying35 files36- Never impose standardized formatting on files with established patterns37- Existing template conventions ALWAYS override these guidelines3839## Financial models4041### Color Coding Standards4243Unless otherwise stated by the user or existing template4445#### Industry-Standard Color Conventions4647- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change48 for scenarios49- **Black text (RGB: 0,0,0)**: ALL formulas and calculations50- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same51 workbook52- **Red text (RGB: 255,0,0)**: External links to other files53- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or54 cells that need to be updated5556### Number Formatting Standards5758#### Required Format Rules5960- **Years**: Format as text strings (e.g., "2024" not "2,024")61- **Currency**: Use $#,##0 format; ALWAYS specify units in headers62 ("Revenue ($mm)")63- **Zeros**: Use number formatting to make all zeros "-", including percentages64 (e.g., "$#,##0;($#,##0);-")65- **Percentages**: Default to 0.0% format (one decimal)66- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)67- **Negative numbers**: Use parentheses (123) not minus -1236869### Formula Construction Rules7071#### Assumptions Placement7273- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate74 assumption cells75- Use cell references instead of hardcoded values in formulas76- Example: Use =B5*(1+$B$6) instead of =B5*1.057778#### Formula Error Prevention7980- Verify all cell references are correct81- Check for off-by-one errors in ranges82- Ensure consistent formulas across all projection periods83- Test with edge cases (zero values, negative numbers)84- Verify no unintended circular references8586#### Documentation Requirements for Hardcodes8788- Comment or in cells beside (if end of table). Format:89 "Source: [System/Document], [Date], [Specific Reference],90 [URL if applicable]"91- Examples:92 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"93 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"94 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"95 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"9697## XLSX creation, editing, and analysis9899## Overview100101A user may ask you to create, edit, or analyze the contents of an .xlsx file.102You have different tools and workflows available for different tasks.103104## Important Requirements105106**LibreOffice Required for Formula Recalculation**: You can assume LibreOffice107is installed for recalculating formula values using the `scripts/recalc.py`108script. The script automatically configures LibreOffice on first run, including109in sandboxed environments where Unix sockets are restricted (handled by110`scripts/office/soffice.py`)111112## Reading and analyzing data113114### Data analysis with pandas115116For data analysis, visualization, and basic operations, use **pandas** which117provides powerful data manipulation capabilities:118119```python120import pandas as pd121122# Read Excel123df = pd.read_excel('file.xlsx') # Default: first sheet124all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict125126# Analyze127df.head() # Preview data128df.info() # Column info129df.describe() # Statistics130131# Write Excel132df.to_excel('output.xlsx', index=False)133```134135## Excel File Workflows136137## CRITICAL: Use Formulas, Not Hardcoded Values138139**Always use Excel formulas instead of calculating values in Python and140hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.141142### WRONG - Hardcoding Calculated Values143144```python145# Bad: Calculating in Python and hardcoding result146total = df['Sales'].sum()147sheet['B10'] = total # Hardcodes 5000148149# Bad: Computing growth rate in Python150growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']151sheet['C5'] = growth # Hardcodes 0.15152153# Bad: Python calculation for average154avg = sum(values) / len(values)155sheet['D20'] = avg # Hardcodes 42.5156```157158### CORRECT - Using Excel Formulas159160```python161# Good: Let Excel calculate the sum162sheet['B10'] = '=SUM(B2:B9)'163164# Good: Growth rate as Excel formula165sheet['C5'] = '=(C4-C2)/C2'166167# Good: Average using Excel function168sheet['D20'] = '=AVERAGE(D2:D19)'169```170171This applies to ALL calculations - totals, percentages, ratios, differences,172etc. The spreadsheet should be able to recalculate when source data changes.173174## Common Workflow1751761. **Choose tool**: pandas for data, openpyxl for formulas/formatting1772. **Create/Load**: Create new workbook or load existing file1783. **Modify**: Add/edit data, formulas, and formatting1794. **Save**: Write to file1805. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the181 scripts/recalc.py script182183 ```bash184 python scripts/recalc.py output.xlsx185 ```1861876. **Verify and fix any errors**:188 - The script returns JSON with error details189 - If `status` is `errors_found`, check `error_summary` for specific error190 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 not257calculated values. Use the provided `scripts/recalc.py` script to recalculate258formulas:259260```bash261python scripts/recalc.py <excel_file> [timeout_seconds]262```263264Example:265266```bash267python scripts/recalc.py output.xlsx 30268```269270The script:271272- Automatically sets up LibreOffice macro on first run273- Recalculates all formulas in all sheets274- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)275- Returns JSON with detailed error locations and counts276- Works on both Linux and macOS277278## Formula Verification Checklist279280Quick checks to ensure formulas work correctly:281282### Essential Verification283284- [ ] **Test 2-3 sample references**: Verify they pull correct values before285 building full model286- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL,287 not BK)288- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 =289 Excel row 6)290291### Common Pitfalls292293- [ ] **NaN handling**: Check for null values with `pd.notna()`294- [ ] **Far-right columns**: FY data often in columns 50+295- [ ] **Multiple matches**: Search all occurrences, not just first296- [ ] **Division by zero**: Check denominators before using `/` in formulas297 (#DIV/0!)298- [ ] **Wrong references**: Verify all cell references point to intended cells299 (#REF!)300- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking301 sheets302303### Formula Testing Strategy304305- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly306- [ ] **Verify dependencies**: Check all cells referenced in formulas exist307- [ ] **Test edge cases**: Include zero, negative, and very large values308309### Interpreting scripts/recalc.py Output310311The script returns JSON with error details:312313```json314{315 "status": "success", // or "errors_found"316 "total_errors": 0, // Total error count317 "total_formulas": 42, // Number of formulas in file318 "error_summary": { // Only present if errors found319 "#REF!": {320 "count": 2,321 "locations": ["Sheet1!B5", "Sheet1!C10"]322 }323 }324}325```326327## Best Practices328329### Library Selection330331- **pandas**: Best for data analysis, bulk operations, and simple data export332- **openpyxl**: Best for complex formatting, formulas, and Excel-specific333 features334335### Working with openpyxl336337- Cell indices are 1-based (row=1, column=1 refers to cell A1)338- Use `data_only=True` to read calculated values:339 `load_workbook('file.xlsx', data_only=True)`340- **Warning**: If opened with `data_only=True` and saved, formulas are replaced341 with values and permanently lost342- For large files: Use `read_only=True` for reading or `write_only=True` for343 writing344- Formulas are preserved but not evaluated - use scripts/recalc.py to update345 values346347### Working with pandas348349- Specify data types to avoid inference issues:350 `pd.read_excel('file.xlsx', dtype={'id': str})`351- For large files, read specific columns:352 `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`353- Handle dates properly:354 `pd.read_excel('file.xlsx', parse_dates=['date_column'])`355356## Code Style Guidelines357358**IMPORTANT**: When generating Python code for Excel operations:359360- Write minimal, concise Python code without unnecessary comments361- Avoid verbose variable names and redundant operations362- Avoid unnecessary print statements363364**For Excel files themselves**:365366- Add comments to cells with complex formulas or important assumptions367- Document data sources for hardcoded values368- Include notes for key calculations and model sections