Skip to main content

Requirements for Outputs

Table of Contents

  1. When to Use This Skill
  2. How to Use This Skill
  3. All Excel files
  4. Financial models
  5. Overview
  6. Important Requirements
  7. Reading and analyzing data
  8. Excel File Workflows
  9. CRITICAL: Use Formulas, Not Hardcoded Values
  10. Common Workflow
  11. Recalculating formulas
  12. Formula Verification Checklist
  13. Best Practices
  14. Code Style Guidelines
  15. Success Output
  16. Completion Checklist
  17. Failure Indicators
  18. When NOT to Use
  19. Anti-Patterns (Avoid)
  20. Principles
  21. Integration

When to Use This Skill

Use this skill when working with XLSX document generation or manipulation in your codebase.

How to Use This Skill

  1. Review the patterns and examples below
  2. Apply the relevant patterns to your XLSX implementation
  3. Follow the best practices outlined in this skill

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)

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

See workflow.md for detailed common workflow content.

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 recalc.py <excel_file> [timeout_seconds]

Example:

python 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

  • Test 2-3 sample references: Verify they pull correct values before building full model
  • Column mapping: Confirm Excel columns match (e.g., column 64 = BL, not BK)
  • Row offset: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)

Common Pitfalls

  • NaN handling: Check for null values with pd.notna()
  • Far-right columns: FY data often in columns 50+
  • Multiple matches: Search all occurrences, not just first
  • Division by zero: Check denominators before using / in formulas (#DIV/0!)
  • Wrong references: Verify all cell references point to intended cells (#REF!)
  • Cross-sheet references: Use correct format (Sheet1!A1) for linking sheets

Formula Testing Strategy

  • Start small: Test formulas on 2-3 cells before applying broadly
  • Verify dependencies: Check all cells referenced in formulas exist
  • Test edge cases: Include zero, negative, and very large values

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

Success Output

When successful, this skill MUST output:

✅ SKILL COMPLETE: xlsx

Completed:
- [x] Excel file created/modified at [path]
- [x] Formulas recalculated (if applicable)
- [x] Zero formula errors verified (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
- [x] Formatting applied per standards (colors, number formats)

Outputs:
- [path/to/file.xlsx]

Verification:
- Formula count: [N] formulas
- Error count: 0 (REQUIRED)

Completion Checklist

Before marking this skill as complete, verify:

  • Excel file exists at expected path
  • If using formulas: python recalc.py output.xlsx executed successfully
  • Formula error check shows status: "success" with total_errors: 0
  • Color coding follows standards (blue=inputs, black=formulas, green=links, red=external)
  • Number formatting applied (currency with units, zeros as "-", percentages)
  • All hardcoded values documented with source comments
  • File opens without errors in Excel/LibreOffice

Failure Indicators

This skill has FAILED if:

  • ❌ Formula errors detected (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
  • ❌ recalc.py returns status: "errors_found"
  • ❌ File not created at expected path
  • ❌ pandas/openpyxl import errors
  • ❌ Hardcoded values used in formulas instead of cell references
  • ❌ File corrupted or cannot be opened
  • ❌ Color coding standards violated in financial models
  • ❌ Missing source documentation for hardcoded inputs

When NOT to Use

Do NOT use this skill when:

  • Simple CSV is sufficient (use pandas to_csv() instead)
  • No formulas, formatting, or multiple sheets needed (use CSV)
  • Read-only data analysis (use pandas read_excel() with data_only=True)
  • Binary Excel files (.xls) required (use xlrd/xlwt instead)
  • Real-time collaboration needed (use Google Sheets API instead)

Use alternatives:

  • CSV files: pandas read_csv/to_csv for simple tabular data
  • Google Sheets: gspread library for cloud collaboration
  • Database: SQLite/PostgreSQL for large datasets with queries

Anti-Patterns (Avoid)

Anti-PatternProblemSolution
Hardcoding calculated valuesBreaks when source data changesUse Excel formulas (=SUM, =AVERAGE)
Using data_only=True then savingPermanently deletes all formulasUse data_only only for reading
Not recalculating formulasCell values show 0 or old valuesAlways run recalc.py after saving
Ignoring formula errorsDelivers broken spreadsheetsCheck recalc.py output for errors
Missing number formattingUnclear units, hard to readApply formats: $#,##0, 0.0%, "2024"
No source documentationCan't verify hardcoded inputsAdd comments with source/date/URL
Inconsistent color codingConfusing for financial modelsFollow blue/black/green/red standard
Large files with read/write modeMemory exhaustionUse read_only/write_only for large files

Principles

This skill embodies:

  • #1 Zero Defects - Formula errors are unacceptable; verify with recalc.py
  • #5 Eliminate Ambiguity - Color coding and number formatting clarify meaning
  • #6 Clear, Understandable, Explainable - Formulas > hardcoded values; document sources
  • #8 No Assumptions - Test with edge cases (zeros, negatives, large values)
  • #10 First Principles - Use Excel's calculation engine, not Python math

Reference Standards:

  • Financial modeling color conventions (blue/black/green/red)
  • Number formatting standards (currency units, zero display, percentages)
  • Formula construction rules (assumptions in separate cells)

Integration

Related Components:

  • Skill: Related skills in the same track