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
Visual Table Design (MUST for new tables unless user/template says otherwise)
- Apply zebra striping in data regions (not headers or totals), using low-contrast alternating fills (for example
#FFFFFF and #F7F9FC)
- Apply thin, light borders for structure (for example
#D9DEE7), favoring outer border + row separators over heavy full-grid borders
- For subtotal/total emphasis, use hierarchy cues (bold text and/or top border emphasis) instead of thick borders around every cell
KPI Visual Hierarchy (MUST when KPI-like metrics exist)
- Highlight an appropriate number of key metrics based on content complexity, prioritizing summary rows, current-period critical values, and exceptions
- Keep highlight treatment consistent (prefer bold + light fill) and avoid overusing saturated colors
- Keep color semantics consistent across the workbook (for example green=positive, red=risk)
- Add short labels near highlighted metrics when helpful (for example "Core KPI", "Exception")
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 IPC restrictions may apply (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.
⚠️ REQUIRED: Pre-Build Planning
Before writing any data/formulas/code, you MUST complete these planning steps:
Step 1: Problem Review
- Read all relevant files (source Excel/CSV/TSV, template workbook, and referenced documents)
- Combine file findings with the user query and restate the task intent in concrete terms
Step 2: Output Detailed Workbook Plan
Present a structured plan covering:
Sheet Plan
- Total number of sheets
- Each sheet name
- Purpose of each sheet
Schema Plan (per sheet)
- Row fields (if row-oriented)
- Column fields (if column-oriented)
- Value source/calculation for each field (raw source / lookup / formula / aggregation)
Style Plan (per sheet)
- Header style (fill, font color, emphasis)
- Zebra striping design
- KPI visual hierarchy design
Required planning output format:
## Problem Review
- Files read: ...
- Task understanding: ...
## Detailed Plan
### Sheet Plan
1. Sheet: <name> — Purpose: <purpose>
### Schema Plan
1. Sheet: <name>
- Row fields: ...
- Column fields: ...
- Value source/calculation: ...
### Style Plan
1. Sheet: <name>
- Header: ...
- Zebra striping: ...
- KPI hierarchy: ...
If inputs are incomplete, still output this plan with explicit assumptions first.
Only proceed to implementation after:
Common Workflow
- Output plan first (MANDATORY): Output Problem Review + Detailed Plan using the required format above
- 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 Linux, macOS, and Windows
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'])
Reusable Styling Helpers (openpyxl)
Use helper functions so visual rules are applied consistently instead of ad-hoc cell formatting:
from openpyxl.styles import PatternFill, Border, Side, Font
ZEBRA_FILL_1 = PatternFill(fill_type="solid", fgColor="FFFFFF")
ZEBRA_FILL_2 = PatternFill(fill_type="solid", fgColor="F7F9FC")
KPI_FILL = PatternFill(fill_type="solid", fgColor="EAF2FF")
THIN_BORDER = Border(
left=Side(style="thin", color="D9DEE7"),
right=Side(style="thin", color="D9DEE7"),
top=Side(style="thin", color="D9DEE7"),
bottom=Side(style="thin", color="D9DEE7"),
)
TOP_EMPHASIS_BORDER = Border(
left=Side(style="thin", color="D9DEE7"),
right=Side(style="thin", color="D9DEE7"),
top=Side(style="medium", color="AAB4C5"),
bottom=Side(style="thin", color="D9DEE7"),
)
def apply_zebra_style(ws, min_row, max_row, min_col, max_col):
for r in range(min_row, max_row + 1):
fill = ZEBRA_FILL_1 if (r - min_row) % 2 == 0 else ZEBRA_FILL_2
for c in range(min_col, max_col + 1):
ws.cell(r, c).fill = fill
def apply_light_borders(ws, min_row, max_row, min_col, max_col):
for r in range(min_row, max_row + 1):
for c in range(min_col, max_col + 1):
ws.cell(r, c).border = THIN_BORDER
def highlight_kpis(ws, cells, label_col=None, label_text=None):
# cells example: ["F5", "F12", "F20"]
for ref in cells:
cell = ws[ref]
cell.fill = KPI_FILL
cell.font = Font(bold=True, color="1F2937")
if label_col and label_text and cells:
ws[f"{label_col}{ws[cells[0]].row}"] = label_text
# Example usage:
# apply_zebra_style(ws, min_row=2, max_row=30, min_col=1, max_col=8)
# apply_light_borders(ws, min_row=1, max_row=30, min_col=1, max_col=8)
# highlight_kpis(ws, cells=["F5", "F12"], label_col="G", label_text="Core KPI")
# ws["A31"].border = TOP_EMPHASIS_BORDER # subtotal/total row emphasis
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: Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, 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 references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.4license: Proprietary. LICENSE.txt has complete terms5---67# Requirements for Outputs89## All Excel files1011### Professional Font12- Use a consistent, professional font (e.g., Arial, Times New Roman) for all deliverables unless otherwise instructed by the user1314### Zero Formula Errors15- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)1617### Preserve Existing Templates (when updating templates)18- Study and EXACTLY match existing format, style, and conventions when modifying files19- Never impose standardized formatting on files with established patterns20- Existing template conventions ALWAYS override these guidelines2122### Visual Table Design (MUST for new tables unless user/template says otherwise)23- Apply zebra striping in data regions (not headers or totals), using low-contrast alternating fills (for example `#FFFFFF` and `#F7F9FC`)24- Apply thin, light borders for structure (for example `#D9DEE7`), favoring outer border + row separators over heavy full-grid borders25- For subtotal/total emphasis, use hierarchy cues (bold text and/or top border emphasis) instead of thick borders around every cell2627### KPI Visual Hierarchy (MUST when KPI-like metrics exist)28- Highlight an appropriate number of key metrics based on content complexity, prioritizing summary rows, current-period critical values, and exceptions29- Keep highlight treatment consistent (prefer bold + light fill) and avoid overusing saturated colors30- Keep color semantics consistent across the workbook (for example green=positive, red=risk)31- Add short labels near highlighted metrics when helpful (for example "Core KPI", "Exception")3233## Financial models3435### Color Coding Standards36Unless otherwise stated by the user or existing template3738#### Industry-Standard Color Conventions39- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios40- **Black text (RGB: 0,0,0)**: ALL formulas and calculations41- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook42- **Red text (RGB: 255,0,0)**: External links to other files43- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated4445### Number Formatting Standards4647#### Required Format Rules48- **Years**: Format as text strings (e.g., "2024" not "2,024")49- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")50- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")51- **Percentages**: Default to 0.0% format (one decimal)52- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)53- **Negative numbers**: Use parentheses (123) not minus -1235455### Formula Construction Rules5657#### Assumptions Placement58- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells59- Use cell references instead of hardcoded values in formulas60- Example: Use =B5*(1+$B$6) instead of =B5*1.056162#### Formula Error Prevention63- Verify all cell references are correct64- Check for off-by-one errors in ranges65- Ensure consistent formulas across all projection periods66- Test with edge cases (zero values, negative numbers)67- Verify no unintended circular references6869#### Documentation Requirements for Hardcodes70- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"71- Examples:72 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"73 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"74 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"75 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"7677# XLSX creation, editing, and analysis7879## Overview8081A 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.8283## Important Requirements8485**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 IPC restrictions may apply (handled by `scripts/office/soffice.py`)8687## Reading and analyzing data8889### Data analysis with pandas90For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:9192```python93import pandas as pd9495# Read Excel96df = pd.read_excel('file.xlsx') # Default: first sheet97all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict9899# Analyze100df.head() # Preview data101df.info() # Column info102df.describe() # Statistics103104# Write Excel105df.to_excel('output.xlsx', index=False)106```107108## Excel File Workflows109110## CRITICAL: Use Formulas, Not Hardcoded Values111112**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.113114### ❌ WRONG - Hardcoding Calculated Values115```python116# Bad: Calculating in Python and hardcoding result117total = df['Sales'].sum()118sheet['B10'] = total # Hardcodes 5000119120# Bad: Computing growth rate in Python121growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']122sheet['C5'] = growth # Hardcodes 0.15123124# Bad: Python calculation for average125avg = sum(values) / len(values)126sheet['D20'] = avg # Hardcodes 42.5127```128129### ✅ CORRECT - Using Excel Formulas130```python131# Good: Let Excel calculate the sum132sheet['B10'] = '=SUM(B2:B9)'133134# Good: Growth rate as Excel formula135sheet['C5'] = '=(C4-C2)/C2'136137# Good: Average using Excel function138sheet['D20'] = '=AVERAGE(D2:D19)'139```140141This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.142143## ⚠️ REQUIRED: Pre-Build Planning144145**Before writing any data/formulas/code, you MUST complete these planning steps:**146147### Step 1: Problem Review148- Read all relevant files (source Excel/CSV/TSV, template workbook, and referenced documents)149- Combine file findings with the user query and restate the task intent in concrete terms150151### Step 2: Output Detailed Workbook Plan152Present a structured plan covering:1531541. **Sheet Plan**155 - Total number of sheets156 - Each sheet name157 - Purpose of each sheet1581592. **Schema Plan (per sheet)**160 - Row fields (if row-oriented)161 - Column fields (if column-oriented)162 - Value source/calculation for each field (raw source / lookup / formula / aggregation)1631643. **Style Plan (per sheet)**165 - Header style (fill, font color, emphasis)166 - Zebra striping design167 - KPI visual hierarchy design168169**Required planning output format:**170```markdown171## Problem Review172- Files read: ...173- Task understanding: ...174175## Detailed Plan176### Sheet Plan1771. Sheet: <name> — Purpose: <purpose>178179### Schema Plan1801. Sheet: <name>181- Row fields: ...182- Column fields: ...183- Value source/calculation: ...184185### Style Plan1861. Sheet: <name>187- Header: ...188- Zebra striping: ...189- KPI hierarchy: ...190```191192If inputs are incomplete, still output this plan with explicit assumptions first.193194**Only proceed to implementation after:**195- [ ] Problem Review is complete196- [ ] Detailed Workbook Plan is output197198## Common Workflow1991. **Output plan first (MANDATORY)**: Output Problem Review + Detailed Plan using the required format above2002. **Choose tool**: pandas for data, openpyxl for formulas/formatting2013. **Create/Load**: Create new workbook or load existing file2024. **Modify**: Add/edit data, formulas, and formatting2035. **Save**: Write to file2046. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the scripts/recalc.py script205 ```bash206 python scripts/recalc.py output.xlsx207 ```2087. **Verify and fix any errors**: 209 - The script returns JSON with error details210 - If `status` is `errors_found`, check `error_summary` for specific error types and locations211 - Fix the identified errors and recalculate again212 - Common errors to fix:213 - `#REF!`: Invalid cell references214 - `#DIV/0!`: Division by zero215 - `#VALUE!`: Wrong data type in formula216 - `#NAME?`: Unrecognized formula name217218### Creating new Excel files219220```python221# Using openpyxl for formulas and formatting222from openpyxl import Workbook223from openpyxl.styles import Font, PatternFill, Alignment224225wb = Workbook()226sheet = wb.active227228# Add data229sheet['A1'] = 'Hello'230sheet['B1'] = 'World'231sheet.append(['Row', 'of', 'data'])232233# Add formula234sheet['B2'] = '=SUM(A1:A10)'235236# Formatting237sheet['A1'].font = Font(bold=True, color='FF0000')238sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')239sheet['A1'].alignment = Alignment(horizontal='center')240241# Column width242sheet.column_dimensions['A'].width = 20243244wb.save('output.xlsx')245```246247### Editing existing Excel files248249```python250# Using openpyxl to preserve formulas and formatting251from openpyxl import load_workbook252253# Load existing file254wb = load_workbook('existing.xlsx')255sheet = wb.active # or wb['SheetName'] for specific sheet256257# Working with multiple sheets258for sheet_name in wb.sheetnames:259 sheet = wb[sheet_name]260 print(f"Sheet: {sheet_name}")261262# Modify cells263sheet['A1'] = 'New Value'264sheet.insert_rows(2) # Insert row at position 2265sheet.delete_cols(3) # Delete column 3266267# Add new sheet268new_sheet = wb.create_sheet('NewSheet')269new_sheet['A1'] = 'Data'270271wb.save('modified.xlsx')272```273274## Recalculating formulas275276Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided `scripts/recalc.py` script to recalculate formulas:277278```bash279python scripts/recalc.py <excel_file> [timeout_seconds]280```281282Example:283```bash284python scripts/recalc.py output.xlsx 30285```286287The script:288- Automatically sets up LibreOffice macro on first run289- Recalculates all formulas in all sheets290- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)291- Returns JSON with detailed error locations and counts292- Works on Linux, macOS, and Windows293294## Formula Verification Checklist295296Quick checks to ensure formulas work correctly:297298### Essential Verification299- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model300- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)301- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)302303### Common Pitfalls304- [ ] **NaN handling**: Check for null values with `pd.notna()`305- [ ] **Far-right columns**: FY data often in columns 50+ 306- [ ] **Multiple matches**: Search all occurrences, not just first307- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)308- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)309- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets310311### Formula Testing Strategy312- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly313- [ ] **Verify dependencies**: Check all cells referenced in formulas exist314- [ ] **Test edge cases**: Include zero, negative, and very large values315316### Interpreting scripts/recalc.py Output317The script returns JSON with error details:318```json319{320 "status": "success", // or "errors_found"321 "total_errors": 0, // Total error count322 "total_formulas": 42, // Number of formulas in file323 "error_summary": { // Only present if errors found324 "#REF!": {325 "count": 2,326 "locations": ["Sheet1!B5", "Sheet1!C10"]327 }328 }329}330```331332## Best Practices333334### Library Selection335- **pandas**: Best for data analysis, bulk operations, and simple data export336- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features337338### Working with openpyxl339- Cell indices are 1-based (row=1, column=1 refers to cell A1)340- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`341- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost342- For large files: Use `read_only=True` for reading or `write_only=True` for writing343- Formulas are preserved but not evaluated - use scripts/recalc.py to update values344345### Working with pandas346- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`347- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`348- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`349350### Reusable Styling Helpers (openpyxl)351Use helper functions so visual rules are applied consistently instead of ad-hoc cell formatting:352353```python354from openpyxl.styles import PatternFill, Border, Side, Font355356ZEBRA_FILL_1 = PatternFill(fill_type="solid", fgColor="FFFFFF")357ZEBRA_FILL_2 = PatternFill(fill_type="solid", fgColor="F7F9FC")358KPI_FILL = PatternFill(fill_type="solid", fgColor="EAF2FF")359THIN_BORDER = Border(360 left=Side(style="thin", color="D9DEE7"),361 right=Side(style="thin", color="D9DEE7"),362 top=Side(style="thin", color="D9DEE7"),363 bottom=Side(style="thin", color="D9DEE7"),364)365TOP_EMPHASIS_BORDER = Border(366 left=Side(style="thin", color="D9DEE7"),367 right=Side(style="thin", color="D9DEE7"),368 top=Side(style="medium", color="AAB4C5"),369 bottom=Side(style="thin", color="D9DEE7"),370)371372def apply_zebra_style(ws, min_row, max_row, min_col, max_col):373 for r in range(min_row, max_row + 1):374 fill = ZEBRA_FILL_1 if (r - min_row) % 2 == 0 else ZEBRA_FILL_2375 for c in range(min_col, max_col + 1):376 ws.cell(r, c).fill = fill377378def apply_light_borders(ws, min_row, max_row, min_col, max_col):379 for r in range(min_row, max_row + 1):380 for c in range(min_col, max_col + 1):381 ws.cell(r, c).border = THIN_BORDER382383def highlight_kpis(ws, cells, label_col=None, label_text=None):384 # cells example: ["F5", "F12", "F20"]385 for ref in cells:386 cell = ws[ref]387 cell.fill = KPI_FILL388 cell.font = Font(bold=True, color="1F2937")389 if label_col and label_text and cells:390 ws[f"{label_col}{ws[cells[0]].row}"] = label_text391392# Example usage:393# apply_zebra_style(ws, min_row=2, max_row=30, min_col=1, max_col=8)394# apply_light_borders(ws, min_row=1, max_row=30, min_col=1, max_col=8)395# highlight_kpis(ws, cells=["F5", "F12"], label_col="G", label_text="Core KPI")396# ws["A31"].border = TOP_EMPHASIS_BORDER # subtotal/total row emphasis397```398399## Code Style Guidelines400**IMPORTANT**: When generating Python code for Excel operations:401- Write minimal, concise Python code without unnecessary comments402- Avoid verbose variable names and redundant operations403- Avoid unnecessary print statements404405**For Excel files themselves**:406- Add comments to cells with complex formulas or important assumptions407- Document data sources for hardcoded values408- Include notes for key calculations and model sections