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
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)
MANDATORY: Preview Data Before Analysis
Before ANY data analysis, run the preview script to safely inspect the file:
python /mnt/skills/public/xlsx/preview_data.py <file_path>
# Options: --rows 20 (show more rows), --cols 30 (show more columns)
The script automatically:
- Checks file size and limits rows for large files (>1MB → first 500 rows)
- Shows shape, column types, first N rows, and statistics
- Truncates wide columns to prevent context overflow
FORBIDDEN PATTERNS — NEVER use on large files:
df.to_string() — produces megabytes of text, overflows context window
print(df) on full dataframe — same problem
df.to_csv() to stdout — same problem
After preview, work with specific data:
# Targeted analysis (safe)
df['column_name'].value_counts()
df.groupby('category')['value'].mean()
df = pd.read_excel('file.xlsx', usecols=['Name', 'Revenue'])
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 /mnt/skills/public/xlsx/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 /mnt/skills/public/xlsx/recalc.py <excel_file> [timeout_seconds]
Example:
python /mnt/skills/public/xlsx/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: xlsx3description: Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Assistant 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 Errors12- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1314### Preserve Existing Templates (when updating templates)15- Study and EXACTLY match existing format, style, and conventions when modifying files16- Never impose standardized formatting on files with established patterns17- Existing template conventions ALWAYS override these guidelines1819## Financial models2021### Color Coding Standards22Unless otherwise stated by the user or existing template2324#### Industry-Standard Color Conventions25- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios26- **Black text (RGB: 0,0,0)**: ALL formulas and calculations27- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook28- **Red text (RGB: 255,0,0)**: External links to other files29- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated3031### Number Formatting Standards3233#### Required Format Rules34- **Years**: Format as text strings (e.g., "2024" not "2,024")35- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")36- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")37- **Percentages**: Default to 0.0% format (one decimal)38- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)39- **Negative numbers**: Use parentheses (123) not minus -1234041### Formula Construction Rules4243#### Assumptions Placement44- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells45- Use cell references instead of hardcoded values in formulas46- Example: Use =B5*(1+$B$6) instead of =B5*1.054748#### Formula Error Prevention49- Verify all cell references are correct50- Check for off-by-one errors in ranges51- Ensure consistent formulas across all projection periods52- Test with edge cases (zero values, negative numbers)53- Verify no unintended circular references5455#### Documentation Requirements for Hardcodes56- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"57- Examples:58 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"59 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"60 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"61 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"6263# XLSX creation, editing, and analysis6465## Overview6667A 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.6869## Important Requirements7071**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 run7273## Reading and analyzing data7475### Data analysis with pandas76For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:7778```python79import pandas as pd8081# Read Excel82df = pd.read_excel('file.xlsx') # Default: first sheet83all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict8485# Analyze86df.head() # Preview data87df.info() # Column info88df.describe() # Statistics8990# Write Excel91df.to_excel('output.xlsx', index=False)92```9394### MANDATORY: Preview Data Before Analysis9596Before ANY data analysis, run the preview script to safely inspect the file:9798```bash99python /mnt/skills/public/xlsx/preview_data.py <file_path>100# Options: --rows 20 (show more rows), --cols 30 (show more columns)101```102103The script automatically:104- Checks file size and limits rows for large files (>1MB → first 500 rows)105- Shows shape, column types, first N rows, and statistics106- Truncates wide columns to prevent context overflow107108**FORBIDDEN PATTERNS — NEVER use on large files:**109- `df.to_string()` — produces megabytes of text, overflows context window110- `print(df)` on full dataframe — same problem111- `df.to_csv()` to stdout — same problem112113**After preview, work with specific data:**114```python115# Targeted analysis (safe)116df['column_name'].value_counts()117df.groupby('category')['value'].mean()118df = pd.read_excel('file.xlsx', usecols=['Name', 'Revenue'])119```120121## Excel File Workflows122123## CRITICAL: Use Formulas, Not Hardcoded Values124125**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.126127### ❌ WRONG - Hardcoding Calculated Values128```python129# Bad: Calculating in Python and hardcoding result130total = df['Sales'].sum()131sheet['B10'] = total # Hardcodes 5000132133# Bad: Computing growth rate in Python134growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']135sheet['C5'] = growth # Hardcodes 0.15136137# Bad: Python calculation for average138avg = sum(values) / len(values)139sheet['D20'] = avg # Hardcodes 42.5140```141142### ✅ CORRECT - Using Excel Formulas143```python144# Good: Let Excel calculate the sum145sheet['B10'] = '=SUM(B2:B9)'146147# Good: Growth rate as Excel formula148sheet['C5'] = '=(C4-C2)/C2'149150# Good: Average using Excel function151sheet['D20'] = '=AVERAGE(D2:D19)'152```153154This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.155156## Common Workflow1571. **Choose tool**: pandas for data, openpyxl for formulas/formatting1582. **Create/Load**: Create new workbook or load existing file1593. **Modify**: Add/edit data, formulas, and formatting1604. **Save**: Write to file1615. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the recalc.py script162 ```bash163 python /mnt/skills/public/xlsx/recalc.py output.xlsx164 ```1656. **Verify and fix any errors**: 166 - The script returns JSON with error details167 - If `status` is `errors_found`, check `error_summary` for specific error types and locations168 - Fix the identified errors and recalculate again169 - Common errors to fix:170 - `#REF!`: Invalid cell references171 - `#DIV/0!`: Division by zero172 - `#VALUE!`: Wrong data type in formula173 - `#NAME?`: Unrecognized formula name174175### Creating new Excel files176177```python178# Using openpyxl for formulas and formatting179from openpyxl import Workbook180from openpyxl.styles import Font, PatternFill, Alignment181182wb = Workbook()183sheet = wb.active184185# Add data186sheet['A1'] = 'Hello'187sheet['B1'] = 'World'188sheet.append(['Row', 'of', 'data'])189190# Add formula191sheet['B2'] = '=SUM(A1:A10)'192193# Formatting194sheet['A1'].font = Font(bold=True, color='FF0000')195sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')196sheet['A1'].alignment = Alignment(horizontal='center')197198# Column width199sheet.column_dimensions['A'].width = 20200201wb.save('output.xlsx')202```203204### Editing existing Excel files205206```python207# Using openpyxl to preserve formulas and formatting208from openpyxl import load_workbook209210# Load existing file211wb = load_workbook('existing.xlsx')212sheet = wb.active # or wb['SheetName'] for specific sheet213214# Working with multiple sheets215for sheet_name in wb.sheetnames:216 sheet = wb[sheet_name]217 print(f"Sheet: {sheet_name}")218219# Modify cells220sheet['A1'] = 'New Value'221sheet.insert_rows(2) # Insert row at position 2222sheet.delete_cols(3) # Delete column 3223224# Add new sheet225new_sheet = wb.create_sheet('NewSheet')226new_sheet['A1'] = 'Data'227228wb.save('modified.xlsx')229```230231## Recalculating formulas232233Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided `recalc.py` script to recalculate formulas:234235```bash236python /mnt/skills/public/xlsx/recalc.py <excel_file> [timeout_seconds]237```238239Example:240```bash241python /mnt/skills/public/xlsx/recalc.py output.xlsx 30242```243244The script:245- Automatically sets up LibreOffice macro on first run246- Recalculates all formulas in all sheets247- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)248- Returns JSON with detailed error locations and counts249- Works on both Linux and macOS250251## Formula Verification Checklist252253Quick checks to ensure formulas work correctly:254255### Essential Verification256- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model257- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)258- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)259260### Common Pitfalls261- [ ] **NaN handling**: Check for null values with `pd.notna()`262- [ ] **Far-right columns**: FY data often in columns 50+ 263- [ ] **Multiple matches**: Search all occurrences, not just first264- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)265- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)266- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets267268### Formula Testing Strategy269- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly270- [ ] **Verify dependencies**: Check all cells referenced in formulas exist271- [ ] **Test edge cases**: Include zero, negative, and very large values272273### Interpreting recalc.py Output274The script returns JSON with error details:275```json276{277 "status": "success", // or "errors_found"278 "total_errors": 0, // Total error count279 "total_formulas": 42, // Number of formulas in file280 "error_summary": { // Only present if errors found281 "#REF!": {282 "count": 2,283 "locations": ["Sheet1!B5", "Sheet1!C10"]284 }285 }286}287```288289## Best Practices290291### Library Selection292- **pandas**: Best for data analysis, bulk operations, and simple data export293- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features294295### Working with openpyxl296- Cell indices are 1-based (row=1, column=1 refers to cell A1)297- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`298- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost299- For large files: Use `read_only=True` for reading or `write_only=True` for writing300- Formulas are preserved but not evaluated - use recalc.py to update values301302### Working with pandas303- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`304- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`305- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`306307## Code Style Guidelines308**IMPORTANT**: When generating Python code for Excel operations:309- Write minimal, concise Python code without unnecessary comments310- Avoid verbose variable names and redundant operations311- Avoid unnecessary print statements312313**For Excel files themselves**:314- Add comments to cells with complex formulas or important assumptions315- Document data sources for hardcoded values316- Include notes for key calculations and model sections