Artifact requirements
All Excel files
Professional font
- Use a consistent professional font (e.g., Arial, Times New Roman) for all artifacts unless the user specifies otherwise
Zero formula errors
- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
Preserving 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 templates
- Existing template conventions ALWAYS override this guidance
Financial models
Color coding standards
Unless the user or an existing template specifies otherwise
Industry 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): References pulling from other sheets in the same workbook
- Red text (RGB: 255,0,0): External references to other files
- Yellow background (RGB: 255,255,0): Key assumptions requiring attention or cells that must be updated
Number formatting standards
Required format rules
- Years: Formatted as text strings (e.g., "2024", not "2,024")
- Currency: Use the format $#,##0; ALWAYS specify units in headers ("Revenue ($mm)")
- Zeros: Use number formatting so all zeros display as "-", including percentages (e.g., "$#,##0;($#,##0);-")
- Percentages: Default to 0.0% format (one decimal)
- Multiples: Formatted as 0.0x for valuation multiples (EV/EBITDA, P/E)
- Negative numbers: Use parentheses (123), not a minus -123
Formula construction rules
Assumption placement
- Place ALL assumptions (growth rates, margins, multiples, etc.) in dedicated assumption cells
- Use cell references instead of hardcoded values in formulas
- Example: use =B5*(1+$B$6) instead of =B5*1.05
Preventing formula errors
- Verify correctness of all cell references
- Check for off-by-one errors in ranges
- Ensure formula consistency across all forecast periods
- Test edge cases (zero values, negative numbers)
- Verify there are no unintended circular references
Hardcode documentation requirements
- Comment in or in adjacent cells (if at the end of a 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"
Creating, editing, and analyzing XLSX
Overview
The user may ask you to create, edit, or analyze the contents of an .xlsx file. Different tools and workflows are available for different tasks.
Important requirements
LibreOffice is required for formula recalculation: You may assume that LibreOffice is installed for recalculating formula values via the scripts/recalc.py script. The script automatically configures LibreOffice on first run, including in sandbox 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 computing values in Python and hardcoding them. This ensures the spreadsheet remains dynamic and updatable.
❌ WRONG — hardcoding computed 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 — sums, 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 a new workbook or load an existing file
- Modify: Add/edit data, formulas, and formatting
- Save: Write to a file
- Recalculate formulas (REQUIRED WHEN 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')
Formula recalculation
Excel files created or modified by openpyxl contain formulas as strings, but not computed values. Use the bundled 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 configures the LibreOffice macro on first run
- Recalculates all formulas across all sheets
- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)
- Returns JSON with detailed error locations and counts
- Works on Linux and macOS
Formula verification checklist
Quick checks to confirm 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 exports
- openpyxl: Best for complex formatting, formulas, and Excel-specific features
Working with openpyxl
- Cell indices are 1-based (row=1, column=1 references cell A1)
- Use
data_only=True to read computed values: load_workbook('file.xlsx', data_only=True)
- Warning: If you open with
data_only=True and save, formulas are replaced with values and lost permanently
- 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 refresh 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 correctly:
pd.read_excel('file.xlsx', parse_dates=['date_column'])
Code style guide
IMPORTANT: When generating Python code for Excel operations:
- Write minimal, concise Python without unnecessary comments
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements
For the Excel files themselves:
- Add cell comments to complex formulas or important assumptions
- Document data sources for hardcoded values
- Include notes for key calculations and model sections
1---2name: xlsx3description: Use this skill whenever a spreadsheet file is the primary input or output. This includes any task in which the user wants to: open, read, edit, or repair an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., add columns, compute formulas, formatting, charts, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user mentions a spreadsheet file by name or path — even in passing (e.g., "the xlsx in my downloads") — and wants something done with it or produced from it. Also trigger when cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into normal spreadsheets. The artifact must be a spreadsheet file. Do NOT trigger when the primary artifact is a Word document, an HTML report, a standalone Python script, a database pipeline, or a Google Sheets API integration, even if tabular data is involved.4---56# Artifact requirements78## All Excel files910### Professional font11- Use a consistent professional font (e.g., Arial, Times New Roman) for all artifacts unless the user specifies otherwise1213### Zero formula errors14- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1516### Preserving 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 templates19- Existing template conventions ALWAYS override this guidance2021## Financial models2223### Color coding standards24Unless the user or an existing template specifies otherwise2526#### Industry 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)**: References pulling from other sheets in the same workbook30- **Red text (RGB: 255,0,0)**: External references to other files31- **Yellow background (RGB: 255,255,0)**: Key assumptions requiring attention or cells that must be updated3233### Number formatting standards3435#### Required format rules36- **Years**: Formatted as text strings (e.g., "2024", not "2,024")37- **Currency**: Use the format $#,##0; ALWAYS specify units in headers ("Revenue ($mm)")38- **Zeros**: Use number formatting so all zeros display as "-", including percentages (e.g., "$#,##0;($#,##0);-")39- **Percentages**: Default to 0.0% format (one decimal)40- **Multiples**: Formatted as 0.0x for valuation multiples (EV/EBITDA, P/E)41- **Negative numbers**: Use parentheses (123), not a minus -1234243### Formula construction rules4445#### Assumption placement46- Place ALL assumptions (growth rates, margins, multiples, etc.) in dedicated assumption cells47- Use cell references instead of hardcoded values in formulas48- Example: use =B5*(1+$B$6) instead of =B5*1.054950#### Preventing formula errors51- Verify correctness of all cell references52- Check for off-by-one errors in ranges53- Ensure formula consistency across all forecast periods54- Test edge cases (zero values, negative numbers)55- Verify there are no unintended circular references5657#### Hardcode documentation requirements58- Comment in or in adjacent cells (if at the end of a 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# Creating, editing, and analyzing XLSX6667## Overview6869The user may ask you to create, edit, or analyze the contents of an .xlsx file. Different tools and workflows are available for different tasks.7071## Important requirements7273**LibreOffice is required for formula recalculation**: You may assume that LibreOffice is installed for recalculating formula values via the `scripts/recalc.py` script. The script automatically configures LibreOffice on first run, including in sandbox environments where Unix sockets are restricted (handled by `scripts/office/soffice.py`)7475## Reading and analyzing data7677### Data analysis with pandas78For data analysis, visualization, and basic operations, use **pandas**, which provides powerful data manipulation capabilities:7980```python81import pandas as pd8283# Read Excel84df = pd.read_excel('file.xlsx') # Default: first sheet85all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict8687# Analyze88df.head() # Preview data89df.info() # Column info90df.describe() # Statistics9192# Write Excel93df.to_excel('output.xlsx', index=False)94```9596## Excel file workflows9798## CRITICAL: use formulas, not hardcoded values99100**Always use Excel formulas instead of computing values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updatable.101102### ❌ WRONG — hardcoding computed values103```python104# Bad: Calculating in Python and hardcoding result105total = df['Sales'].sum()106sheet['B10'] = total # Hardcodes 5000107108# Bad: Computing growth rate in Python109growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']110sheet['C5'] = growth # Hardcodes 0.15111112# Bad: Python calculation for average113avg = sum(values) / len(values)114sheet['D20'] = avg # Hardcodes 42.5115```116117### ✅ CORRECT — using Excel formulas118```python119# Good: Let Excel calculate the sum120sheet['B10'] = '=SUM(B2:B9)'121122# Good: Growth rate as Excel formula123sheet['C5'] = '=(C4-C2)/C2'124125# Good: Average using Excel function126sheet['D20'] = '=AVERAGE(D2:D19)'127```128129This applies to ALL calculations — sums, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.130131## Common workflow1321. **Choose tool**: pandas for data, openpyxl for formulas/formatting1332. **Create/Load**: Create a new workbook or load an existing file1343. **Modify**: Add/edit data, formulas, and formatting1354. **Save**: Write to a file1365. **Recalculate formulas (REQUIRED WHEN USING FORMULAS)**: Use the scripts/recalc.py script137 ```bash138 python scripts/recalc.py output.xlsx139 ```1406. **Verify and fix any errors**:141 - The script returns JSON with error details142 - If `status` is `errors_found`, check `error_summary` for specific error types and locations143 - Fix the identified errors and recalculate again144 - Common errors to fix:145 - `#REF!`: Invalid cell references146 - `#DIV/0!`: Division by zero147 - `#VALUE!`: Wrong data type in formula148 - `#NAME?`: Unrecognized formula name149150### Creating new Excel files151152```python153# Using openpyxl for formulas and formatting154from openpyxl import Workbook155from openpyxl.styles import Font, PatternFill, Alignment156157wb = Workbook()158sheet = wb.active159160# Add data161sheet['A1'] = 'Hello'162sheet['B1'] = 'World'163sheet.append(['Row', 'of', 'data'])164165# Add formula166sheet['B2'] = '=SUM(A1:A10)'167168# Formatting169sheet['A1'].font = Font(bold=True, color='FF0000')170sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')171sheet['A1'].alignment = Alignment(horizontal='center')172173# Column width174sheet.column_dimensions['A'].width = 20175176wb.save('output.xlsx')177```178179### Editing existing Excel files180181```python182# Using openpyxl to preserve formulas and formatting183from openpyxl import load_workbook184185# Load existing file186wb = load_workbook('existing.xlsx')187sheet = wb.active # or wb['SheetName'] for specific sheet188189# Working with multiple sheets190for sheet_name in wb.sheetnames:191 sheet = wb[sheet_name]192 print(f"Sheet: {sheet_name}")193194# Modify cells195sheet['A1'] = 'New Value'196sheet.insert_rows(2) # Insert row at position 2197sheet.delete_cols(3) # Delete column 3198199# Add new sheet200new_sheet = wb.create_sheet('NewSheet')201new_sheet['A1'] = 'Data'202203wb.save('modified.xlsx')204```205206## Formula recalculation207208Excel files created or modified by openpyxl contain formulas as strings, but not computed values. Use the bundled `scripts/recalc.py` script to recalculate formulas:209210```bash211python scripts/recalc.py <excel_file> [timeout_seconds]212```213214Example:215```bash216python scripts/recalc.py output.xlsx 30217```218219The script:220- Automatically configures the LibreOffice macro on first run221- Recalculates all formulas across all sheets222- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)223- Returns JSON with detailed error locations and counts224- Works on Linux and macOS225226## Formula verification checklist227228Quick checks to confirm formulas work correctly:229230### Essential verification231- [ ] **Test 2-3 sample references**: Verify they pull the correct values before building the full model232- [ ] **Column matching**: Confirm Excel columns line up (e.g., column 64 = BL, not BK)233- [ ] **Row offsets**: Remember that Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)234235### Common pitfalls236- [ ] **NaN handling**: Check for null values via `pd.notna()`237- [ ] **Right-side columns**: FY data is often in columns 50+238- [ ] **Multiple matches**: Look for all occurrences, not just the first239- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)240- [ ] **Bad references**: Verify all cell references point to the intended cells (#REF!)241- [ ] **Cross-sheet references**: Use the correct format (Sheet1!A1) for linked sheets242243### Formula testing strategy244- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly245- [ ] **Verify dependencies**: Confirm all cells referenced by formulas exist246- [ ] **Test edge cases**: Include zero, negative, and very large values247248### Interpreting scripts/recalc.py output249The script returns JSON with error details:250```json251{252 "status": "success", // or "errors_found"253 "total_errors": 0, // Total error count254 "total_formulas": 42, // Number of formulas in file255 "error_summary": { // Only present if errors found256 "#REF!": {257 "count": 2,258 "locations": ["Sheet1!B5", "Sheet1!C10"]259 }260 }261}262```263264## Best practices265266### Library selection267- **pandas**: Best for data analysis, bulk operations, and simple data exports268- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features269270### Working with openpyxl271- Cell indices are 1-based (row=1, column=1 references cell A1)272- Use `data_only=True` to read computed values: `load_workbook('file.xlsx', data_only=True)`273- **Warning**: If you open with `data_only=True` and save, formulas are replaced with values and lost permanently274- For large files: use `read_only=True` for reading or `write_only=True` for writing275- Formulas are preserved but not evaluated — use scripts/recalc.py to refresh values276277### Working with pandas278- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`279- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`280- Handle dates correctly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`281282## Code style guide283**IMPORTANT**: When generating Python code for Excel operations:284- Write minimal, concise Python without unnecessary comments285- Avoid verbose variable names and redundant operations286- Avoid unnecessary print statements287288**For the Excel files themselves**:289- Add cell comments to complex formulas or important assumptions290- Document data sources for hardcoded values291- Include notes for key calculations and model sections