How to Work with Excel Files Using the xlsx Skill: A Complete Guide
The xlsx skill provides a complete workflow for creating, reading, editing, and validating Excel workbooks using pandas for data manipulation, openpyxl for formula injection, and LibreOffice for error-free formula recalculation.
The xlsx skill in the anthropics/skills repository offers a robust, standardized approach to work with Excel files using the xlsx skill architecture. This self-contained module separates concerns between human-readable specifications, Python data libraries, and automated formula validation to ensure zero-error outputs.
Core Architecture of the xlsx Skill
The skill separates three distinct concerns to maintain reliability and consistency:
Guidance and Standards
The human-readable specification lives in skills/xlsx/SKILL.md. This file defines required fonts, error-free formulas, template preservation rules, and the step-by-step process that every agent must follow when manipulating Excel files.
Python Libraries
- pandas serves as the default for bulk data manipulation, including loading, summarizing, and writing tabular data.
- openpyxl handles low-level workbook operations such as inserting formulas, applying styles, and managing multiple sheets. The specification explicitly recommends openpyxl whenever formulas or formatting are required.
Formula Recalculation Engine
LibreOffice evaluates Excel formulas that openpyxl cannot compute. The helper script skills/xlsx/scripts/recalc.py installs a tiny StarBasic macro, launches LibreOffice headless, forces a full workbook calculation, and parses the resulting file for error codes (#REF!, #DIV/0!, etc.). The script returns a JSON summary that agents use to decide whether additional fixes are required.
Step-by-Step Workflow to Work with Excel Files
Because the skill enforces zero formula errors, the recalc step is mandatory for any workbook containing formulas.
- Pick the right library – Use pandas for quick data extraction, openpyxl when you need to preserve or inject formulas.
- Create or load a workbook – Either start from
Workbook()or callload_workbook()withdata_only=Falseto keep formulas intact. - Write data and formulas – Follow the "Never hard-code calculated values" rule; insert Excel formulas as strings (e.g.,
'=SUM(A2:A10)'). - Save the file –
wb.save('myfile.xlsx'). - Recalculate – Run
python scripts/recalc.py myfile.xlsx [timeout]. The script updates all formula results and produces a JSON error report. - Validate – Parse the JSON; if
statusiserrors_found, fix the reported cells and repeat step 5.
Practical Code Examples
Loading and Modifying Existing Workbooks
This example demonstrates using pandas for data analysis and openpyxl for formula injection:
import pandas as pd
from openpyxl import load_workbook
# Load data (first sheet) with pandas
df = pd.read_excel('input.xlsx')
print(df.head())
# Add a new column that will be calculated in Excel
df['Total'] = None # placeholder, will be filled by a formula later
# Save intermediate CSV (optional)
df.to_csv('intermediate.csv', index=False)
# Load the workbook with openpyxl to inject the formula
wb = load_workbook('input.xlsx')
ws = wb.active
# Assuming data starts at row 2 and column A
last_row = ws.max_row
ws[f'D{last_row+1}'] = '=SUM(C2:C{last_row})' # Excel formula, not a Python value
# Save the updated workbook
wb.save('output.xlsx')
Creating New Workbooks with Formatting
This example creates a formatted financial model from scratch:
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
ws = wb.active
ws.title = 'Revenue'
# Header row
headers = ['Year', 'Revenue ($mm)']
for col, header in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = Font(bold=True, color='FFFFFFFF')
cell.fill = PatternFill('solid', start_color='FF0000FF')
cell.alignment = Alignment(horizontal='center')
# Sample data
data = [(2023, 150), (2024, 165), (2025, 180)]
for r, (year, rev) in enumerate(data, start=2):
ws[f'A{r}'] = year
ws[f'B{r}'] = rev
# Add a total row with formula
ws[f'A{len(data)+2}'] = 'Total'
ws[f'B{len(data)+2}'] = f'=SUM(B2:B{len(data)+1})'
# Adjust column widths
ws.column_dimensions['A'].width = 12
ws.column_dimensions['B'].width = 18
wb.save('financial_model.xlsx')
Recalculating Formulas and Validating Output
After saving any workbook containing formulas, run the recalculation script:
python skills/xlsx/scripts/recalc.py financial_model.xlsx 30
Sample output (formatted for readability):
{
"status": "success",
"total_errors": 0,
"total_formulas": 4,
"error_summary": {}
}
If errors were present, error_summary would list each error type with cell locations, allowing you to programmatically locate and fix them before delivering the final file.
Key Files and Components
| File | Purpose |
|---|---|
skills/xlsx/SKILL.md |
Human-readable specification: standards, workflow, and best-practice checklist. |
skills/xlsx/scripts/recalc.py |
LibreOffice-based formula recalculation, error detection, and JSON reporting. |
skills/xlsx/scripts/office/soffice.py |
Helper that configures the environment for headless LibreOffice calls (used by recalc.py). |
Python code using pandas (import pandas as pd) or openpyxl (from openpyxl import …) |
Primary runtime dependencies for data manipulation and workbook operations. |
These components together give you a robust, repeatable way to manipulate Excel spreadsheets while guaranteeing the zero-error, formula-driven outputs required by the skill.
Summary
- The xlsx skill enforces a strict workflow to ensure zero formula errors in all Excel outputs.
- Use pandas for bulk data operations and openpyxl when you need formulas, formatting, or multiple sheet management.
- Always run
skills/xlsx/scripts/recalc.pyafter saving workbooks with formulas to validate against error codes like#REF!or#DIV/0!. - The specification in
skills/xlsx/SKILL.mddefines required fonts, template preservation rules, and the mandatory recalculation step. - Never hard-code calculated values; always insert Excel formulas as strings to maintain dynamic calculation capabilities.
Frequently Asked Questions
What is the difference between using pandas and openpyxl in the xlsx skill?
pandas is optimized for bulk data manipulation—loading entire sheets, performing statistical analysis, and exporting tabular data quickly. openpyxl provides low-level access to Excel-specific features like formula injection, cell formatting, chart creation, and multi-sheet workbook management. According to the skill specification in skills/xlsx/SKILL.md, you should use openpyxl whenever your workflow involves formulas or formatting requirements.
Why is the recalc.py script mandatory for workbooks with formulas?
The skills/xlsx/scripts/recalc.py script is mandatory because the xlsx skill enforces a zero formula errors policy. Openpyxl can write formulas but cannot calculate their results or detect errors like #REF! or #DIV/0!. The script launches LibreOffice in headless mode, forces a full workbook recalculation, and returns a JSON report indicating whether any cells contain error values. This validation step ensures that delivered Excel files contain only valid, computable formulas.
How do I preserve existing formulas when loading an existing Excel file?
To preserve existing formulas when loading a workbook, use load_workbook() from openpyxl with the parameter data_only=False. This ensures that openpyxl reads the formula strings (e.g., =SUM(A1:A10)) rather than the cached calculated values. If you set data_only=True, openpyxl will read only the values that were last calculated, and any formulas will be lost when you save the file.
Can I use the xlsx skill without installing LibreOffice?
You can use the pandas and openpyxl components of the xlsx skill without LibreOffice for basic read/write operations and formatting. However, if your workflow involves writing formulas to cells, the skills/xlsx/scripts/recalc.py script requires LibreOffice to validate those formulas and ensure zero errors. Without this validation step, you cannot guarantee that your formulas are error-free, violating the core requirement of the xlsx skill specification.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →