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
Formula Evaluation: openpyxl writes formulas as strings; calculated values are produced by Excel/WPS/LibreOffice when the file is opened. Verify formulas by reading the file back and checking that cell references point to the intended cells. (The bundled recalc.py is a deprecated placeholder that always reports unsupported — do not rely on it.)
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
- Verify formulas (MANDATORY IF USING FORMULAS): Read the saved file back and check formula correctness:
- Re-open the file with openpyxl and confirm each formula string references the intended cells (correct rows/columns/sheets)
- Cross-check 2-3 key formulas against a hand-computed expected value
- Common formula errors to watch for:
#REF!: Invalid cell references
#DIV/0!: Division by zero
#VALUE!: Wrong data type in formula
#NAME?: Unrecognized formula name
- Calculated values are produced when the user opens the file in Excel/WPS/LibreOffice
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 evaluation and verification
Excel files created or modified by openpyxl contain formulas as strings but not cached calculated values. This is expected: values are recalculated automatically when the file is opened in Excel, WPS, or LibreOffice.
Verification approach (no headless recalculation):
- Re-open the saved file with
openpyxl.load_workbook(...) and assert each key formula string matches the intended references
- Hand-compute 2-3 expected results in Python and compare against the formula logic
- If a previously calculated file must be read, use
data_only=True to load cached values (do not save from that handle — formulas would be lost)
The bundled recalc.py is a deprecated placeholder: it performs no recalculation and always returns {"status": "unsupported"} with a non-zero exit code. Do not include it in any workflow.
Formula Verification Checklist
Quick checks to ensure formulas work correctly:
Essential Verification
Common Pitfalls
Formula Testing Strategy
Read-back Verification Output
When you re-open the saved file to verify, record for each key formula:
- Cell address and formula string as saved
- Expected reference(s) and whether they match
- Hand-computed expected result vs formula logic (for 2-3 key cells)
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 by openpyxl — values appear when opened in Excel/WPS/LibreOffice
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: excel-table-processing3description: 电子表格创建、编辑和分析,支持公式、格式、数据分析和可视化。适用于处理.xlsx、.xlsm、.csv、.tsv等表格文件:创建带公式和格式的电子表格、读取分析数据、修改保留公式、数据分析可视化4---5# Requirements for Outputs
6
7## All Excel files
8
9### Zero Formula Errors
10- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
11
12### Preserve Existing Templates (when updating templates)
13- Study and EXACTLY match existing format, style, and conventions when modifying files
14- Never impose standardized formatting on files with established patterns
15- Existing template conventions ALWAYS override these guidelines
16
17## Financial models
18
19### Color Coding Standards
20Unless otherwise stated by the user or existing template
21
22#### Industry-Standard Color Conventions
23- **Blue text (RGB: 0,0,255)**: Hardcoded inputs, and numbers users will change for scenarios
24- **Black text (RGB: 0,0,0)**: ALL formulas and calculations
25- **Green text (RGB: 0,128,0)**: Links pulling from other worksheets within same workbook
26- **Red text (RGB: 255,0,0)**: External links to other files
27- **Yellow background (RGB: 255,255,0)**: Key assumptions needing attention or cells that need to be updated
28
29### Number Formatting Standards
30
31#### Required Format Rules
32- **Years**: Format as text strings (e.g., "2024" not "2,024")
33- **Currency**: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")
34- **Zeros**: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")
35- **Percentages**: Default to 0.0% format (one decimal)
36- **Multiples**: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)
37- **Negative numbers**: Use parentheses (123) not minus -123
38
39### Formula Construction Rules
40
41#### Assumptions Placement
42- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells
43- Use cell references instead of hardcoded values in formulas
44- Example: Use =B5*(1+$B$6) instead of =B5*1.05
45
46#### Formula Error Prevention
47- Verify all cell references are correct
48- Check for off-by-one errors in ranges
49- Ensure consistent formulas across all projection periods
50- Test with edge cases (zero values, negative numbers)
51- Verify no unintended circular references
52
53#### Documentation Requirements for Hardcodes
54- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"
55- Examples:
56 - "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"
57 - "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"
58 - "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"
59 - "Source: FactSet, 8/20/2025, Consensus Estimates Screen"
60
61# XLSX creation, editing, and analysis
62
63## Overview
64
65A 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.
66
67## Important Requirements
68
69**Formula Evaluation**: openpyxl writes formulas as strings; calculated values are produced by Excel/WPS/LibreOffice when the file is opened. Verify formulas by reading the file back and checking that cell references point to the intended cells. (The bundled `recalc.py` is a deprecated placeholder that always reports `unsupported` — do not rely on it.)
70
71## Reading and analyzing data
72
73### Data analysis with pandas
74For data analysis, visualization, and basic operations, use **pandas** which provides powerful data manipulation capabilities:
75
76```python
77import pandas as pd
78
79# Read Excel
80df = pd.read_excel('file.xlsx') # Default: first sheet
81all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict
82
83# Analyze
84df.head() # Preview data
85df.info() # Column info
86df.describe() # Statistics
87
88# Write Excel
89df.to_excel('output.xlsx', index=False)
90```
91
92## Excel File Workflows
93
94## CRITICAL: Use Formulas, Not Hardcoded Values
95
96**Always use Excel formulas instead of calculating values in Python and hardcoding them.** This ensures the spreadsheet remains dynamic and updateable.
97
98### ❌ WRONG - Hardcoding Calculated Values
99```python
100# Bad: Calculating in Python and hardcoding result
101total = df['Sales'].sum()
102sheet['B10'] = total # Hardcodes 5000
103
104# Bad: Computing growth rate in Python
105growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
106sheet['C5'] = growth # Hardcodes 0.15
107
108# Bad: Python calculation for average
109avg = sum(values) / len(values)
110sheet['D20'] = avg # Hardcodes 42.5
111```
112
113### ✅ CORRECT - Using Excel Formulas
114```python
115# Good: Let Excel calculate the sum
116sheet['B10'] = '=SUM(B2:B9)'
117
118# Good: Growth rate as Excel formula
119sheet['C5'] = '=(C4-C2)/C2'
120
121# Good: Average using Excel function
122sheet['D20'] = '=AVERAGE(D2:D19)'
123```
124
125This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.
126
127## Common Workflow
1281. **Choose tool**: pandas for data, openpyxl for formulas/formatting
1292. **Create/Load**: Create new workbook or load existing file
1303. **Modify**: Add/edit data, formulas, and formatting
1314. **Save**: Write to file
1325. **Verify formulas (MANDATORY IF USING FORMULAS)**: Read the saved file back and check formula correctness:
133 - Re-open the file with openpyxl and confirm each formula string references the intended cells (correct rows/columns/sheets)
134 - Cross-check 2-3 key formulas against a hand-computed expected value
135 - Common formula errors to watch for:
136 - `#REF!`: Invalid cell references
137 - `#DIV/0!`: Division by zero
138 - `#VALUE!`: Wrong data type in formula
139 - `#NAME?`: Unrecognized formula name
140 - Calculated values are produced when the user opens the file in Excel/WPS/LibreOffice
141
142### Creating new Excel files
143
144```python
145# Using openpyxl for formulas and formatting
146from openpyxl import Workbook
147from openpyxl.styles import Font, PatternFill, Alignment
148
149wb = Workbook()
150sheet = wb.active
151
152# Add data
153sheet['A1'] = 'Hello'
154sheet['B1'] = 'World'
155sheet.append(['Row', 'of', 'data'])
156
157# Add formula
158sheet['B2'] = '=SUM(A1:A10)'
159
160# Formatting
161sheet['A1'].font = Font(bold=True, color='FF0000')
162sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
163sheet['A1'].alignment = Alignment(horizontal='center')
164
165# Column width
166sheet.column_dimensions['A'].width = 20
167
168wb.save('output.xlsx')
169```
170
171### Editing existing Excel files
172
173```python
174# Using openpyxl to preserve formulas and formatting
175from openpyxl import load_workbook
176
177# Load existing file
178wb = load_workbook('existing.xlsx')
179sheet = wb.active # or wb['SheetName'] for specific sheet
180
181# Working with multiple sheets
182for sheet_name in wb.sheetnames:
183 sheet = wb[sheet_name]
184 print(f"Sheet: {sheet_name}")
185
186# Modify cells
187sheet['A1'] = 'New Value'
188sheet.insert_rows(2) # Insert row at position 2
189sheet.delete_cols(3) # Delete column 3
190
191# Add new sheet
192new_sheet = wb.create_sheet('NewSheet')
193new_sheet['A1'] = 'Data'
194
195wb.save('modified.xlsx')
196```
197
198## Formula evaluation and verification
199
200Excel files created or modified by openpyxl contain formulas as strings but not cached calculated values. This is expected: values are recalculated automatically when the file is opened in Excel, WPS, or LibreOffice.
201
202Verification approach (no headless recalculation):
2031. Re-open the saved file with `openpyxl.load_workbook(...)` and assert each key formula string matches the intended references
2042. Hand-compute 2-3 expected results in Python and compare against the formula logic
2053. If a previously calculated file must be read, use `data_only=True` to load cached values (do not save from that handle — formulas would be lost)
206
207> The bundled `recalc.py` is a **deprecated placeholder**: it performs no recalculation and always returns `{"status": "unsupported"}` with a non-zero exit code. Do not include it in any workflow.
208
209## Formula Verification Checklist
210
211Quick checks to ensure formulas work correctly:
212
213### Essential Verification
214- [ ] **Test 2-3 sample references**: Verify they pull correct values before building full model
215- [ ] **Column mapping**: Confirm Excel columns match (e.g., column 64 = BL, not BK)
216- [ ] **Row offset**: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)
217
218### Common Pitfalls
219- [ ] **NaN handling**: Check for null values with `pd.notna()`
220- [ ] **Far-right columns**: FY data often in columns 50+
221- [ ] **Multiple matches**: Search all occurrences, not just first
222- [ ] **Division by zero**: Check denominators before using `/` in formulas (#DIV/0!)
223- [ ] **Wrong references**: Verify all cell references point to intended cells (#REF!)
224- [ ] **Cross-sheet references**: Use correct format (Sheet1!A1) for linking sheets
225
226### Formula Testing Strategy
227- [ ] **Start small**: Test formulas on 2-3 cells before applying broadly
228- [ ] **Verify dependencies**: Check all cells referenced in formulas exist
229- [ ] **Test edge cases**: Include zero, negative, and very large values
230
231### Read-back Verification Output
232When you re-open the saved file to verify, record for each key formula:
233- Cell address and formula string as saved
234- Expected reference(s) and whether they match
235- Hand-computed expected result vs formula logic (for 2-3 key cells)
236
237## Best Practices
238
239### Library Selection
240- **pandas**: Best for data analysis, bulk operations, and simple data export
241- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features
242
243### Working with openpyxl
244- Cell indices are 1-based (row=1, column=1 refers to cell A1)
245- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`
246- **Warning**: If opened with `data_only=True` and saved, formulas are replaced with values and permanently lost
247- For large files: Use `read_only=True` for reading or `write_only=True` for writing
248- Formulas are preserved but not evaluated by openpyxl — values appear when opened in Excel/WPS/LibreOffice
249
250### Working with pandas
251- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`
252- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`
253- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`
254
255## Code Style Guidelines
256**IMPORTANT**: When generating Python code for Excel operations:
257- Write minimal, concise Python code without unnecessary comments
258- Avoid verbose variable names and redundant operations
259- Avoid unnecessary print statements
260
261**For Excel files themselves**:
262- Add comments to cells with complex formulas or important assumptions
263- Document data sources for hardcoded values
264- Include notes for key calculations and model sections