Generated banner for XLSX
Generated logo for XLSX

XLSX

AnthropicOfficialPublished by Anthropic

  • Skill
  • Tool integration
  • Documents and content
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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, .xltx, .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.
— the description by Anthropic

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to managing spreadsheet files (.xlsx, .xlsm, .xltx, .csv, .tsv) by leveraging openpyxl, pandas, and markitdown. It emphasizes professional formatting, formula integrity, and strict adherence to user specifications. The skill includes mandatory recalculation procedures to ensure formula accuracy and provides specific guidelines for financial modeling, including color-coding conventions and numerical formatting standards.

What it does

  • Creates new spreadsheets or modifies existing files with formulas and formatting.
  • Performs bulk data operations using pandas for efficient input and output.
  • Validates formula accuracy and integrity using a dedicated recalculation script.
  • Provides guidelines for financial modeling, including cell styling and assumption documentation.
  • Converts between various tabular file formats while maintaining data structure.
  • Cleans and restructures messy or malformed tabular data into professional spreadsheets.

When to use it

  • When you need to read, edit, or fix existing spreadsheet files.
  • When creating a new spreadsheet from scratch or from external data sources.
  • When you need to ensure formulas in a spreadsheet are accurate and error-free.
  • When you are building financial models that require specific formatting and documentation.
  • When you need to clean up messy or malformed tabular data files.

Advantages

  • Ensures formula reliability through automated recalculation checks.
  • Maintains professional standards for financial models and data presentation.
  • Provides clear conventions for handling complex spreadsheet tasks like merged cells and cross-sheet references.
  • Supports a wide range of file formats including .xlsx, .xlsm, and .csv.
  • Reduces errors by enforcing strict documentation of assumptions and hardcoded values.

Usage examples

“Create a budget spreadsheet for Q3 with columns for Category, Budgeted, and Actual.”
A new .xlsx file is generated with the specified headers, professional formatting, and formulas to calculate variances.
“Fix the formulas in my sales_data.xlsx file and add a summary sheet.”
The agent opens the file, corrects the formulas, adds a summary sheet with appropriate calculations, and verifies the output with the recalculation tool.
“Convert this messy CSV file into a clean, formatted Excel workbook.”
The agent parses the CSV, cleans the data, applies consistent formatting, and saves the result as a structured .xlsx file.
“Update the revenue projections in the financial model using the new growth rate in cell B5.”
The agent modifies the input cell, ensures all dependent formulas are updated, and validates the integrity of the model.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/anthropics/xlsx/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip xlsx.zip -d .agents/skills

Documentation by Anthropic

XLSX creation, editing, and analysis

TaskApproach
Create or edit with formulas/formattingopenpyxl — see gotchas below
Bulk data in or outpandas (read_excel, to_excel)
Quick look at a sheetmarkitdown file.xlsx — ## SheetName per sheet; reads .xlsm too. No cell coordinates, so don't plan edits from it
Read a model (formulas and values)two load_workbook passes — see gotchas

openpyxl, pandas, and markitdown are preinstalled — do not run pip install first; write the script and import directly. Only if an import fails (or the markitdown command is missing): pip install the missing package.

Script paths below are relative to this skill's directory.

Requirements for every output

  • Professional font (Arial, Times New Roman) throughout, unless the user says otherwise.

  • Zero formula errors. Never ship while recalc.py reports errors_found. If you think an error predates you, prove it: load the original with data_only=True and look at that cell. An error you introduced looks exactly like one you inherited.

  • Use formulas, never hardcoded results. Write sheet['B10'] = '=SUM(B2:B9)', not the Python-computed total. The sheet must recalculate when its inputs change.

  • Follow the user's spec literally. Exact tab names, exact column headers, and the formula they spelled out. A redesign that computes something else fails, however elegant.

  • Document every assumption and hardcoded number where the reader will see it — a cell comment, or an adjacent cell at a table's end. Cite a real source when one exists (Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]); when the number came from the user, say so plainly.

  • A workbook you create for someone to fill in needs a short legend naming which cells to edit, and one example row of realistic values showing the expected format. Never add such a row to a file you were asked to edit.

  • Editing an existing file: match its conventions exactly. They override every guideline here. Find its designated input cells first — a distinct font color, fill, or shading marks them — write only there, and leave every existing formula untouched.

Recalculate (mandatory whenever the file contains formulas)

openpyxl writes formulas as strings with no cached values. Until you recalculate, every formula cell reads back as None to anything reading cached values — pandas, load_workbook(data_only=True), and most previewers.

python scripts/recalc.py output.xlsx [timeout_seconds]   # default 30

LibreOffice computes every formula, the file is rewritten in place, and you get JSON: status (success | errors_found), total_formulas, total_errors, and an error_summary naming up to 100 cells per error type (locations_truncated says how many it withheld — trust total_errors, not the length of the list). Fix what it names and run it again. JSON with an error key instead of a status means nothing was recalculated, and only that case exits non-zero — errors_found exits 0, so never treat a clean exit as a clean workbook.

A green recalc proves your formulas evaluate, not that they are right. An off-by-one range or a reference to the wrong row yields a clean, error-free file with wrong numbers. Write 2–3 formulas first and check they pull the values you expect, before building out a grid.

A workbook that links to another file loses those links if you re-save it with openpyxl and then recalculate. Such a formula reads ='[1]Returns Analysis'!$B$2 — the [1] is an index into the workbook's external-reference list, naming a separate file on disk, not a sheet. That file is rarely present here, so the cell's cached value is the only thing holding its data. openpyxl strips that value on save; LibreOffice then has to resolve the reference for real, fails, writes #NAME?, and deletes every link. recalc.py refuses to run in that state — copy those cells' values out of the original before you save over them (--force overrides, and accepts the loss).

Choosing formulas that survive verification

LibreOffice implements fewer functions than Excel, and one it cannot evaluate becomes a literal #NAME? baked into the file you deliver.

  • Prefer Excel-2007-era functions — SUMIFS, INDEX, MATCH, IFERROR, SUMPRODUCT — which need no prefix.

  • Six post-2007 functions work, but only with an _xlfn. prefix, because openpyxl writes your formula into the XML verbatim and Excel stores post-2007 names prefixed (its UI hides the prefix): _xlfn.TEXTJOIN, _xlfn.CONCAT, _xlfn.IFS, _xlfn.SWITCH, _xlfn.MAXIFS, _xlfn.MINIFS. Written bare, each yields #NAME?.

  • Never use XLOOKUP, XMATCH, SORT, FILTER, UNIQUE, or SEQUENCE. The runtime's LibreOffice cannot evaluate them under any prefix. Newer builds do evaluate them, but they are spilling array functions and an openpyxl-written file has no spill metadata, so only the top-left cell of the range gets a value — and recalc.py reports total_errors: 0 on the truncated result. Use INDEX/MATCH for lookups, and sort, filter, and de-duplicate in Python before writing the cells.

  • A formula LibreOffice could not parse is written back lowercased — a quick tell beside a #NAME?.

openpyxl gotchas

  • Reading a model takes two loads. data_only=True yields cached values with the formulas gone; the default yields formula strings with no values. One pass cannot give you both.

  • data_only=True is destructive if you save. That workbook has no formulas left, so saving replaces every one with a literal — permanently.

  • data_only=True on a file openpyxl just wrote returns None everywhere — run recalc.py first. (A formula whose result is "" also reads back as None.)

  • Merged cells: write the top-left anchor only. Every other cell in the range is a MergedCell whose .value is read-only.

  • .xlsm loses its macros unless you pass keep_vba=True to load_workbook.

  • A sheet name containing a space must be quoted in a cross-sheet reference: ='Assumptions Inputs'!$B$5. Unquoted, it evaluates to #VALUE!.

Financial models

Unless the user says otherwise, or the existing file already does something else.

Color: blue text (0,0,255) for hardcoded inputs and scenario levers · black for formulas · green (0,128,0) for links to another sheet · red (255,0,0) for links to another file · yellow fill (255,255,0) for key assumptions and cells the user should fill in.

Numbers: currency $#,##0, with the unit named in the header (Revenue ($mm)) · zeros render as -, including in percentages ($#,##0;($#,##0);-) · negatives in parentheses · percentages 0.0%, stored as fractions (0.15 renders 15.0%; storing 15 renders 1500.0%) · valuation multiples 0.0x · years as text ("2024", never 2,024).

Structure: every assumption in its own labeled cell, referenced by the formulas that use it (=B5*(1+$B$6), never =B5*1.05) · formulas consistent across every projection period, since a lone edited cell mid-row is the commonest silent error · guard denominators that can be zero.

Dependencies

openpyxl, pandas, markitdown (pip, preinstalled — install only if an import fails or the command is missing) · LibreOffice (soffice, auto-configured for sandboxed environments via scripts/office/soffice.py)

Files

scripts/recalc.py

"""
Excel Formula Recalculation Script
Recalculates all formulas in an Excel file using LibreOffice
"""

import contextlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path

from office.soffice import get_soffice_env, run_soffice

from openpyxl import load_workbook

MACRO_FILENAME = "Module1.xba"
SOFFICE_MISSING = "soffice not found on PATH; LibreOffice is required to recalculate"

MAX_LOCATIONS = 100

EXTERNAL_REF_RE = re.compile(r"""(?<![\w"\[])'?\[\d+\][^!"\[\]]*'?!""")

RECALCULATE_MACRO = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
<script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
    Sub RecalculateAndSave()
      ThisComponent.calculateAll()
      ThisComponent.store()
      ThisComponent.close(True)
    End Sub
</script:module>"""


def has_gtimeout():
    try:
        subprocess.run(
            ["gtimeout", "--version"], capture_output=True, timeout=1, check=False
        )
        return True
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


def _stamp(path):
    st = os.stat(path)
    return st.st_mtime_ns, st.st_size


def setup_libreoffice_macro(profile_dir: Path, timeout=30):
    url = profile_dir.as_uri()
    try:
        run_soffice(
            ["--headless", "--terminate_after_init", f"-env:UserInstallation={url}"],
            capture_output=True,
            timeout=timeout,
        )
    except FileNotFoundError:
        return None, SOFFICE_MISSING
    except subprocess.TimeoutExpired:
        return None, "LibreOffice timed out creating its profile; formulas were NOT recalculated"

    macro_dir = profile_dir / "user" / "basic" / "Standard"
    if not macro_dir.exists():
        return None, "LibreOffice did not create a usable profile; formulas were NOT recalculated"

    try:
        (macro_dir / MACRO_FILENAME).write_text(RECALCULATE_MACRO)
    except OSError as e:
        return None, f"Could not install the recalculation macro: {e}"

    return url, None


def external_links_at_risk(filename):
    try:
        with zipfile.ZipFile(filename) as archive:
            names = archive.namelist()
    except (zipfile.BadZipFile, OSError):
        return []
    if not any(n.startswith("xl/externalLinks/") for n in names):
        return []

    with contextlib.ExitStack() as stack:
        formulas = load_workbook(filename, data_only=False)
        stack.callback(formulas.close)
        values = load_workbook(filename, data_only=True)
        stack.callback(values.close)

        external_names = [
            name
            for name, dn in formulas.defined_names.items()
            if isinstance(getattr(dn, "value", None), str) and EXTERNAL_REF_RE.search(dn.value)
        ]
        name_re = (
            re.compile(r"\b(" + "|".join(re.escape(n) for n in external_names) + r")\b")
            if external_names
            else None
        )

        at_risk = []
        for sheet in formulas.sheetnames:
            ws = formulas[sheet]
            if not hasattr(ws, "iter_rows"):  
                continue
            cached = values[sheet]
            for row in ws.iter_rows():
                for cell in row:
                    v = cell.value
                    if not (isinstance(v, str) and v.startswith("=")):
                        continue
                    reaches_out = EXTERNAL_REF_RE.search(v) or (name_re and name_re.search(v))
                    if reaches_out and cached[cell.coordinate].value is None:
                        at_risk.append(f"{sheet}!{cell.coordinate}")
        return at_risk


def recalc(filename, timeout=30, force=False):
    if not Path(filename).exists():
        return {"error": f"File {filename} does not exist"}

    abs_path = str(Path(filename).absolute())

    if not os.access(abs_path, os.W_OK):
        return {"error": f"{filename} is not writable; recalculation rewrites the file in place"}

    try:
        get_soffice_env()
    except Exception as e:  
        return {"error": f"Could not prepare the LibreOffice environment: {e}"}

    if not force:
        try:
            at_risk = external_links_at_risk(filename)
        except Exception as e:  
            return {"error": f"Could not inspect {filename} for external links: {e}"}
        if at_risk:
            shown = at_risk[:MAX_LOCATIONS]
            return {
                "error": (
                    "Refusing to recalculate: this workbook links to another workbook, and "
                    f"{len(at_risk)} linked cell(s) have lost their cached value (openpyxl strips "
                    "these on save). Recalculating would resolve them to #NAME? and delete the "
                    "external links for good. Copy those cells' values from the original file "
                    "before saving, or pass --force to accept the loss. Charts and conditional "
                    "formats can hold external references too, so this list may not be exhaustive."
                ),
                "external_link_cells": shown,
                "external_link_cells_truncated": max(0, len(at_risk) - len(shown)),
            }

    with tempfile.TemporaryDirectory(
        prefix="recalc-lo-profile-", ignore_cleanup_errors=True
    ) as profile_dir:
        return _recalc_with_profile(filename, abs_path, timeout, Path(profile_dir))


def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
    started = time.monotonic()
    profile_url, err = setup_libreoffice_macro(profile_dir, timeout=timeout)
    if err:
        return {"error": err}

    timeout = max(5, int(timeout - (time.monotonic() - started)))

    before = _stamp(abs_path)

    cmd = [
        "soffice",
        "--headless",
        "--norestore",
        f"-env:UserInstallation={profile_url}",
        "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application",
        abs_path,
    ]

    if platform.system() == "Linux" and shutil.which("timeout"):
        cmd = ["timeout", str(timeout)] + cmd
    elif platform.system() == "Darwin" and has_gtimeout():
        cmd = ["gtimeout", str(timeout)] + cmd

    timed_out = f"LibreOffice timed out after {timeout}s; formulas were NOT recalculated. Re-run with a longer timeout."

    try:
        result = subprocess.run(
            cmd, capture_output=True, text=True, env=get_soffice_env(), timeout=timeout + 15
        )
    except subprocess.TimeoutExpired:
        return {"error": timed_out}
    except FileNotFoundError:
        return {"error": SOFFICE_MISSING}

    if result.returncode == 124:
        return {"error": timed_out}

    if result.returncode != 0:
        detail = (result.stderr or "").strip() or f"soffice exited {result.returncode}"
        return {"error": f"LibreOffice failed to recalculate: {detail}"}

    if _stamp(abs_path) == before:
        return {
            "error": (
                "LibreOffice exited cleanly but never rewrote the file, so nothing was "
                "recalculated. Check that no other LibreOffice instance is running, then retry."
            )
        }

    try:
        wb = load_workbook(filename, data_only=True)

        excel_errors = [
            "#VALUE!",
            "#DIV/0!",
            "#REF!",
            "#NAME?",
            "#NULL!",
            "#NUM!",
            "#N/A",
        ]
        error_details = {err: [] for err in excel_errors}
        total_errors = 0

        for sheet_name in wb.sheetnames:
            ws = wb[sheet_name]
            if not hasattr(ws, "iter_rows"):  
                continue
            for row in ws.iter_rows():
                for cell in row:
                    if cell.value is not None and isinstance(cell.value, str):
                        for err in excel_errors:
                            if err in cell.value:
                                location = f"{sheet_name}!{cell.coordinate}"
                                error_details[err].append(location)
                                total_errors += 1
                                break

        result = {
            "status": "success" if total_errors == 0 else "errors_found",
            "total_errors": total_errors,
            "error_summary": {},
        }

        for err_type, locations in error_details.items():
            if locations:
                entry = {"count": len(locations), "locations": locations[:MAX_LOCATIONS]}
                if len(locations) > MAX_LOCATIONS:
                    entry["locations_truncated"] = len(locations) - MAX_LOCATIONS
                result["error_summary"][err_type] = entry

        wb.close()

        wb_formulas = load_workbook(filename, data_only=False)
        formula_count = 0
        for sheet_name in wb_formulas.sheetnames:
            ws = wb_formulas[sheet_name]
            if not hasattr(ws, "iter_rows"):  
                continue
            for row in ws.iter_rows():
                for cell in row:
                    if (
                        cell.value
                        and isinstance(cell.value, str)
                        and cell.value.startswith("=")
                    ):
                        formula_count += 1
        wb_formulas.close()

        result["total_formulas"] = formula_count

        return result

    except Exception as e:
        return {"error": str(e)}


def main():
    args = [a for a in sys.argv[1:] if a != "--force"]
    force = "--force" in sys.argv[1:]

    if not args:
        print("Usage: python recalc.py <excel_file> [timeout_seconds] [--force]")
        print("\nRecalculates all formulas in an Excel file using LibreOffice")
        print("\nReturns JSON with error details:")
        print("  - status: 'success' or 'errors_found'")
        print("  - total_errors: Total number of Excel errors found")
        print("  - total_formulas: Number of formulas in the file")
        print("  - error_summary: Breakdown by error type with locations")
        print("    - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A")
        print("\nOn any failure the JSON has an 'error' key and no 'status'.")
        print("--force recalculates even when it would destroy external links.")
        sys.exit(1)

    filename = args[0]
    timeout = int(args[1]) if len(args) > 1 else 30

    result = recalc(filename, timeout, force=force)
    print(json.dumps(result, indent=2))
    sys.exit(1 if "error" in result else 0)


if __name__ == "__main__":
    main()

Requirements and compatibility

Written for: Claude Code, Claude apps

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Anthropic
Publisher
Anthropic (Official)
Source
anthropics/skills · skills/xlsx · commit 2c5958e
Licence
Apache License 2.0 (redistribution allowed)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Anthropic.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download xlsx.zip