[IMPORTANT] Use TaskCreate to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI may ask user whether to skip.
Quick Summary
Goal: Create, edit, and analyze spreadsheets (.xlsx) with formulas, formatting, and data analysis while ensuring zero formula errors.
Workflow:
- Choose Tool — pandas for data analysis, openpyxl for formulas/formatting
- Create/Modify — Add data, formulas (not calculated values), formatting
- Recalculate — MANDATORY: Run
python recalc.py output.xlsx after formula changes
- Verify — Check recalc.py JSON output, fix any #REF!, #DIV/0!, #VALUE! errors
Key Rules:
- Use Formulas, Not Values:
=SUM(A1:A10) not hardcoded result
- Zero Errors: Deliver with ZERO formula errors (#REF!, #DIV/0!, etc.)
- Financial Models: Blue=inputs, Black=formulas, Green=internal links, Red=external
- Always Recalculate: openpyxl doesn't calculate formulas, LibreOffice does via recalc.py
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)
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 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 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
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: xlsx-113description: [Document Processing] Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude 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---6
7> **[IMPORTANT]** Use `TaskCreate` to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI may ask user whether to skip.
8
9## Quick Summary
10
11**Goal:** Create, edit, and analyze spreadsheets (.xlsx) with formulas, formatting, and data analysis while ensuring zero formula errors.
12
13**Workflow:**
14
151. **Choose Tool** — pandas for data analysis, openpyxl for formulas/formatting
162. **Create/Modify** — Add data, formulas (not calculated values), formatting
173. **Recalculate** — MANDATORY: Run `python recalc.py output.xlsx` after formula changes
184. **Verify** — Check recalc.py JSON output, fix any #REF!, #DIV/0!, #VALUE! errors
19
20**Key Rules:**
21
22- **Use Formulas, Not Values**: `=SUM(A1:A10)` not hardcoded result
23- **Zero Errors**: Deliver with ZERO formula errors (#REF!, #DIV/0!, etc.)
24- **Financial Models**: Blue=inputs, Black=formulas, Green=internal links, Red=external
25- **Always Recalculate**: openpyxl doesn't calculate formulas, LibreOffice does via recalc.py
26
27# Requirements for Outputs
28
29## All Excel files
30
31### Zero Formula Errors
32
33- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
34
35### Preserve Existing Templates (when updating templates)
36
37- Study and EXACTLY match existing format, style, and conventions when modifying files
38- Never impose standardized formatting on files with established patterns
39- Existing template conventions ALWAYS override these guidelines
40
41## Financial models
42
43### Color Coding Standards
44
45Unless otherwise stated by the user or existing template
46
47#### Industry-Standard Color Conventions
48
49- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios
50- **Black text (RGB: 0,0,0)**: ALL formulas and calculations
51- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook
52- **Red text (RGB: 255,0,0)**: External links to other files
53- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated
54
55### Number Formatting Standards
56
57#### Required Format Rules
58
59- **Years**: Format as text strings (e.g., "2024" not "2,024")
60- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")
61- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")
62- **Percentages**: Default to 0.0% format (one decimal)
63- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)
64- **Negative numbers**: Use parentheses (123) not minus -123
65
66### Formula Construction Rules
67
68#### Assumptions Placement
69
70- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells
71- Use cell references instead of hardcoded values in formulas
72- Example: Use =B5*(1+$B$6) instead of =B5*1.05
73
74#### Formula Error Prevention
75
76- Verify all cell references are correct
77- Check for off-by-one errors in ranges
78- Ensure consistent formulas across all projection periods
79- Test with edge cases (zero values, negative numbers)
80- Verify no unintended circular references
81
82#### Documentation Requirements for Hardcodes
83
84- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"
85- Examples:
86 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"
87 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"
88 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"
89 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"
90
91# XLSX creation, editing, and analysis
92
93## Overview
94
95A 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.
96
97## Important Requirements
98
99**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
100
101## Reading and analyzing data
102
103### Data analysis with pandas
104
105For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:
106
107```python
108import pandas as pd
109
110# Read Excel
111df = pd.read_excel('file.xlsx') # Default: first sheet
112all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict
113
114# Analyze
115df.head() # Preview data
116df.info() # Column info
117df.describe() # Statistics
118
119# Write Excel
120df.to_excel('output.xlsx', index=False)
121```
122
123## Excel File Workflows
124
125## CRITICAL: Use Formulas, Not Hardcoded Values
126
127**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.
128
129### ❌ WRONG - Hardcoding Calculated Values
130
131```python
132# Bad: Calculating in Python and hardcoding result
133total = df['Sales'].sum()
134sheet['B10'] = total # Hardcodes 5000
135
136# Bad: Computing growth rate in Python
137growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
138sheet['C5'] = growth # Hardcodes 0.15
139
140# Bad: Python calculation for average
141avg = sum(values) / len(values)
142sheet['D20'] = avg # Hardcodes 42.5
143```
144
145### ✅ CORRECT - Using Excel Formulas
146
147```python
148# Good: Let Excel calculate the sum
149sheet['B10'] = '=SUM(B2:B9)'
150
151# Good: Growth rate as Excel formula
152sheet['C5'] = '=(C4-C2)/C2'
153
154# Good: Average using Excel function
155sheet['D20'] = '=AVERAGE(D2:D19)'
156```
157
158This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.
159
160## Common Workflow
161
1621. **Choose tool**: pandas for data, openpyxl for formulas/formatting
1632. **Create/Load**: Create new workbook or load existing file
1643. **Modify**: Add/edit data, formulas, and formatting
1654. **Save**: Write to file
1665. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the recalc.py script
167 ```bash
168 python recalc.py output.xlsx
169 ```
1706. **Verify and fix any errors**:
171 - The script returns JSON with error details
172 - If `status` is `errors_found`, check `error_summary` for specific error types and locations
173 - Fix the identified errors and recalculate again
174 - Common errors to fix:
175 - `#REF!`: Invalid cell references
176 - `#DIV/0!`: Division by zero
177 - `#VALUE!`: Wrong data type in formula
178 - `#NAME?`: Unrecognized formula name
179
180### Creating new Excel files
181
182```python
183# Using openpyxl for formulas and formatting
184from openpyxl import Workbook
185from openpyxl.styles import Font, PatternFill, Alignment
186
187wb = Workbook()
188sheet = wb.active
189
190# Add data
191sheet['A1'] = 'Hello'
192sheet['B1'] = 'World'
193sheet.append(['Row', 'of', 'data'])
194
195# Add formula
196sheet['B2'] = '=SUM(A1:A10)'
197
198# Formatting
199sheet['A1'].font = Font(bold=True, color='FF0000')
200sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
201sheet['A1'].alignment = Alignment(horizontal='center')
202
203# Column width
204sheet.column_dimensions['A'].width = 20
205
206wb.save('output.xlsx')
207```
208
209### Editing existing Excel files
210
211```python
212# Using openpyxl to preserve formulas and formatting
213from openpyxl import load_workbook
214
215# Load existing file
216wb = load_workbook('existing.xlsx')
217sheet = wb.active # or wb['SheetName'] for specific sheet
218
219# Working with multiple sheets
220for sheet_name in wb.sheetnames:
221 sheet = wb[sheet_name]
222 print(f"Sheet: {sheet_name}")
223
224# Modify cells
225sheet['A1'] = 'New Value'
226sheet.insert_rows(2) # Insert row at position 2
227sheet.delete_cols(3) # Delete column 3
228
229# Add new sheet
230new_sheet = wb.create_sheet('NewSheet')
231new_sheet['A1'] = 'Data'
232
233wb.save('modified.xlsx')
234```
235
236## Recalculating formulas
237
238Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided `recalc.py` script to recalculate formulas:
239
240```bash
241python recalc.py <excel_file> [timeout_seconds]
242```
243
244Example:
245
246```bash
247python recalc.py output.xlsx 30
248```
249
250The script:
251
252- Automatically sets up LibreOffice macro on first run
253- Recalculates all formulas in all sheets
254- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)
255- Returns JSON with detailed error locations and counts
256- Works on both Linux and macOS
257
258## Formula Verification Checklist
259
260Quick checks to ensure formulas work correctly:
261
262### Essential Verification
263
264- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model
265- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)
266- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)
267
268### Common Pitfalls
269
270- [ ] **NaN handling**: Check for null values with `pd.notna()`
271- [ ] **Far-right columns**: FY data often in columns 50+
272- [ ] **Multiple matches**: Search all occurrences, not just first
273- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)
274- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)
275- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets
276
277### Formula Testing Strategy
278
279- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly
280- [ ] **Verify dependencies**: Check all cells referenced in formulas exist
281- [ ] **Test edge cases**: Include zero, negative, and very large values
282
283### Interpreting recalc.py Output
284
285The script returns JSON with error details:
286
287```json
288{
289 "status": "success", // or "errors_found"
290 "total_errors": 0, // Total error count
291 "total_formulas": 42, // Number of formulas in file
292 "error_summary": {
293 // Only present if errors found
294 "#REF!": {
295 "count": 2,
296 "locations": ["Sheet1!B5", "Sheet1!C10"]
297 }
298 }
299}
300```
301
302## Best Practices
303
304### Library Selection
305
306- **pandas**: Best for data analysis, bulk operations, and simple data export
307- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features
308
309### Working with openpyxl
310
311- Cell indices are 1-based (row=1, column=1 refers to cell A1)
312- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`
313- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost
314- For large files: Use `read_only=True` for reading or `write_only=True` for writing
315- Formulas are preserved but not evaluated - use recalc.py to update values
316
317### Working with pandas
318
319- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`
320- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`
321- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`
322
323## Code Style Guidelines
324
325**IMPORTANT**: When generating Python code for Excel operations:
326
327- Write minimal, concise Python code without unnecessary comments
328- Avoid verbose variable names and redundant operations
329- Avoid unnecessary print statements
330
331**For Excel files themselves**:
332
333- Add comments to cells with complex formulas or important assumptions
334- Document data sources for hardcoded values
335- Include notes for key calculations and model sections