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.
Reading and analyzing data
Data analysis with pandas
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)
CRITICAL: Use Formulas, Not Hardcoded Values
Always use Excel formulas instead of calculating values in Python and hardcoding them.
❌ WRONG - Hardcoding Calculated Values
total = df['Sales'].sum()
sheet['B10'] = total # Hardcodes 5000
✅ CORRECT - Using Excel Formulas
sheet['B10'] = '=SUM(B2:B9)'
sheet['C5'] = '=(C4-C2)/C2'
sheet['D20'] = '=AVERAGE(D2:D19)'
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 scripts/recalc.py script
- Verify and fix any errors
Creating new Excel files
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
from openpyxl import load_workbook
wb = load_workbook('existing.xlsx')
sheet = wb.active
# Modify cells
sheet['A1'] = 'New Value'
sheet.insert_rows(2)
sheet.delete_cols(3)
# Add new sheet
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'
wb.save('modified.xlsx')
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)
- 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'])
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# XLSX creation, editing, and analysis89## Overview1011A 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.1213## Important Requirements1415**LibreOffice Required for Formula Recalculation**: You can assume LibreOffice is installed for recalculating formula values using the `scripts/recalc.py` script.1617## Reading and analyzing data1819### Data analysis with pandas20```python21import pandas as pd2223# Read Excel24df = pd.read_excel('file.xlsx') # Default: first sheet25all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # All sheets as dict2627# Analyze28df.head() # Preview data29df.info() # Column info30df.describe() # Statistics3132# Write Excel33df.to_excel('output.xlsx', index=False)34```3536## CRITICAL: Use Formulas, Not Hardcoded Values3738**Always use Excel formulas instead of calculating values in Python and hardcoding them.**3940### ❌ WRONG - Hardcoding Calculated Values41```python42total = df['Sales'].sum()43sheet['B10'] = total # Hardcodes 500044```4546### ✅ CORRECT - Using Excel Formulas47```python48sheet['B10'] = '=SUM(B2:B9)'49sheet['C5'] = '=(C4-C2)/C2'50sheet['D20'] = '=AVERAGE(D2:D19)'51```5253## Common Workflow541. **Choose tool**: pandas for data, openpyxl for formulas/formatting552. **Create/Load**: Create new workbook or load existing file563. **Modify**: Add/edit data, formulas, and formatting574. **Save**: Write to file585. **Recalculate formulas (MANDATORY IF USING FORMULAS)**: Use the scripts/recalc.py script596. **Verify and fix any errors**6061### Creating new Excel files6263```python64from openpyxl import Workbook65from openpyxl.styles import Font, PatternFill, Alignment6667wb = Workbook()68sheet = wb.active6970# Add data71sheet['A1'] = 'Hello'72sheet['B1'] = 'World'73sheet.append(['Row', 'of', 'data'])7475# Add formula76sheet['B2'] = '=SUM(A1:A10)'7778# Formatting79sheet['A1'].font = Font(bold=True, color='FF0000')80sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')81sheet['A1'].alignment = Alignment(horizontal='center')8283# Column width84sheet.column_dimensions['A'].width = 208586wb.save('output.xlsx')87```8889### Editing existing Excel files9091```python92from openpyxl import load_workbook9394wb = load_workbook('existing.xlsx')95sheet = wb.active9697# Modify cells98sheet['A1'] = 'New Value'99sheet.insert_rows(2)100sheet.delete_cols(3)101102# Add new sheet103new_sheet = wb.create_sheet('NewSheet')104new_sheet['A1'] = 'Data'105106wb.save('modified.xlsx')107```108109## Best Practices110111### Library Selection112- **pandas**: Best for data analysis, bulk operations, and simple data export113- **openpyxl**: Best for complex formatting, formulas, and Excel-specific features114115### Working with openpyxl116- Cell indices are 1-based (row=1, column=1 refers to cell A1)117- Use `data_only=True` to read calculated values: `load_workbook('file.xlsx', data_only=True)`118- For large files: Use `read_only=True` for reading or `write_only=True` for writing119- Formulas are preserved but not evaluated - use scripts/recalc.py to update values120121### Working with pandas122- Specify data types to avoid inference issues: `pd.read_excel('file.xlsx', dtype={'id': str})`123- For large files, read specific columns: `pd.read_excel('file.xlsx', usecols=['A', 'C', 'E'])`124- Handle dates properly: `pd.read_excel('file.xlsx', parse_dates=['date_column'])`