xlsx-tools-mcp

io.github.ruriazz由 GitHub 帳號 ruriazz 發布v0.3.2更新於 Oct 24, 2026

MCP server for accurate, structure-preserving read/write access to Excel (.xlsx) files

已驗證STDIO僅桌面檔案與儲存資料與分析

概覽

AI 產生的概覽

本機 MCP 伺服器,提供 29 個工具,讓助理讀取、查詢與編輯 Excel .xlsx 活頁簿,並盡量保留原有結構、樣式與公式。

可以做什麼
  • 列出預先載入的活頁簿、工作表和中介資料,讀取儲存格範圍或單一儲存格及其格式細節
  • 跨工作表搜尋數值,剖析工作表資料,並以 pandas 運算式篩選與彙總列
  • 建立活頁簿和工作表,寫入值與公式,附加列,插入或刪除列與欄
  • 重新命名、複製、合併、取消合併與清除範圍,設定儲存格樣式,自動調整欄寬,建立原生表格與圖表
  • 透過無介面 LibreOffice 重算公式並回報公式錯誤,以及還原 .bak 備份
適用情境
適合助理需要直接檢視或修改使用者電腦上真實 Excel 檔案(而非純 CSV)的情境,尤其是編輯後必須保留原有格式、公式與版面時。也適合在試算表內進行資料剖析、篩選與彙總。
執行需求
以 stdio 本機程序執行,來自 PyPI 套件,需要 Python 3.10 以上版本,通常以 uvx 或 pip 啟動。LibreOffice 為選用但建議安裝,用於公式重算。選用環境變數:XLSX_MCP_FILES、XLSX_MCP_ALLOWED_DIRS、XLSX_MCP_AUTO_BACKUP、XLSX_MCP_BACKUP_DIR、XLSX_MCP_LOCK_TIMEOUT、XLSX_MCP_RECALC_TIMEOUT。
安裝前請注意
寫入類工具會修改真實檔案,並可刪除工作表、列欄與範圍;建議設定 XLSX_MCP_ALLOWED_DIRS 限制存取範圍,並保持 XLSX_MCP_AUTO_BACKUP 開啟。LibreOffice 重算會重新匯出整份活頁簿,樞紐分析表、圖表、資料驗證與部分格式可能無法完全原樣保留。公式注入防護可透過 allow_external_formulas 繞過,因而允許外部或 DDE 類公式。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 xlsx-tools-mcp,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

xlsx-tools-mcp

An MCP server for reading and writing Excel (.xlsx) files with high accuracy, while preserving the file's existing structure, styles, and formulas.

[CI] [PyPI Version] [Downloads/month] [Listed on mcpservers.org]


Overview

xlsx-tools-mcp exposes 29 Model Context Protocol (MCP) tools that give an LLM agent accurate, structure-preserving read and write access to Excel .xlsx files. It runs as a standard stdio MCP server: you install it and register it with an MCP client (Claude Code, OpenCode, etc.), and the client's agent can list sheets, read cell ranges, search values, aggregate data, write cells/formulas, manage sheets/rows/columns, apply styles, and force formula recalculation.

It is built around the principle that editing an existing workbook should not destroy what it doesn't touch.

Features

  • Structure-preserving writes via openpyxl — writes load the existing workbook and save it back, preserving styles, merged cells, comments, and any aspect the edit doesn't touch.
  • Never-stale formula results via LibreOffice recalculation — openpyxl writes formula strings but never evaluates them. After every value/formula write the server runs a headless LibreOffice pass to recompute real results, then returns errors_found — any Excel error values (#REF!, #DIV/0!, #N/A, …) produced by the recalculation.
  • Fast reads via python-calamine — a Rust-backed parser for accurate, fast type inference, with an automatic openpyxl fallback when you need formulas/styles/comments or when calamine can't parse the file.
  • pandas-based grouping/aggregation & querying — aggregate_sheet and query_sheet perform operations without destroying source structure, equipped with AST expression validation to block code injection.
  • Native Excel objects — create formal Excel Tables (create_table) with autofilter and styles, and native charts (create_chart for bar, line, pie, scatter).
  • Sheet lifecycle & formatting — rename sheets (rename_sheet), duplicate sheets with styles intact (copy_sheet), clear ranges (clear_range), and auto-fit column widths (autofit_columns).
  • Cross-platform reliability (Windows, macOS, Linux) — case-insensitive path confinement, comma or semicolon ; environment delimiters, safe atomic file replacement with transient lock retry (WinError 32 / antivirus defense), and silent headless recalculation without window flicker.
  • Per-file locking — concurrent tool calls (or other processes) touching the same workbook are serialized via a sibling <path>.lock file (filelock), so writes never interleave and corrupt the file.
  • Path confinement — XLSX_MCP_ALLOWED_DIRS (comma or semicolon-separated) restricts all reads and writes to specific directories. If set, any attempt to access a file outside these boundaries raises AccessDeniedError. Case-insensitive path comparisons and multi-drive paths on Windows are supported.
  • Auto-backup & restore — Write tools automatically create a .bak sibling file before modifying the workbook if backup=True (which defaults to XLSX_MCP_AUTO_BACKUP=true). Use restore_backup to atomically revert changes.
  • Formula injection guard — write_cells and append_rows reject formulas containing WEBSERVICE, HYPERLINK, INDIRECT, RTD, CALL, REGISTER, or DDE commands (|) by default to prevent data exfiltration or malicious links. Pass allow_external_formulas=True to bypass this check.
  • XML-bomb protection — the defusedxml package is an automatic dependency; openpyxl detects it and uses its hardened XML parser, so hostile xlsx XML can't expand into resource exhaustion.
  • Preload files at startup — set XLSX_MCP_FILES to preload one or more workbooks (comma or semicolon-separated); tools can then be called with path omitted or with a short alias instead of a full filesystem path.

Download Stats

[Downloads/month] [Downloads/week]

Live via pypistats.org, non-mirror downloads. These count download events, not unique users or installs — one user can trigger many downloads (CI, reinstalls, Docker rebuilds, mirrors).


Architecture

┌──────────────────────── Supervisor (MCP transport, stdio)│  src/xlsx_tools_mcp/server.py     29 MCP tools + instructions│  src/xlsx_tools_mcp/settings.py   env vars, preloaded files, path resolution│  src/xlsx_tools_mcp/locking.py    per-file <path>.lock serialization│  src/xlsx_tools_mcp/errors.py     domain error types│  src/xlsx_tools_mcp/recalc.py     LibreOffice headless recalc + error scanning│├─ Read path│  src/xlsx_tools_mcp/io/reader.py      calamine primary → openpyxl fallback│  src/xlsx_tools_mcp/io/transform.py   pandas aggregation on read results│└─ Write path   src/xlsx_tools_mcp/io/writer.py      openpyxl → LibreOffice recalc → scan errors

The io layer (io/) is deliberately decoupled from the MCP transport (server.py). Each MCP tool is a thin wrapper that resolves the target path, takes the per-file lock, and calls one io-layer function. This keeps the core logic independent of MCP, so it can be tested directly (see tests/).

The recalculation tradeoff

After a write that touches cell values or formulas, the server runs soffice --headless --convert-to xlsx on the file so every formula gets a real computed value. This round-trip recomputes formulas but re-exports the whole workbook — it is a tradeoff, not a guarantee of bit-perfect preservation. Features that openpyxl would otherwise preserve may not survive identically: pivot tables, charts, data validation, some formats, and some defined names.

If you're working on a structurally complex workbook where that risk matters, you can pass recalculate=False on the value/formula-writing tools (write_cells, append_rows, insert_rows, delete_rows, insert_columns, delete_columns) to save with openpyxl only and skip the round-trip entirely.


Requirements

  • Python ≥ 3.10
  • LibreOffice — optional but recommended. Needed only for formula recalculation. Without it, writes still succeed (saved via openpyxl) but formulas are not recomputed and a warning is returned in the message field.

Install LibreOffice:

bash
# macOSbrew install --cask libreoffice
# Debian / Ubuntusudo apt-get install -y libreoffice-calc
# Windowswinget install TheDocumentFoundation.LibreOffice

The server finds LibreOffice by checking soffice / libreoffice on PATH, the standard macOS install location (/Applications/LibreOffice.app/Contents/MacOS/soffice), and standard Windows paths (%ProgramFiles%\LibreOffice\program\soffice.exe, etc.). On Windows, headless recalculation runs silently without window flicker (CREATE_NO_WINDOW) and with isolated user profiles.


Installation

The server speaks stdio transport (standard MCP): after installation it waits for an MCP client to connect and call tools. You don't usually run it yourself; you register it with a client.

1. From PyPI via uvx (recommended — no clone)

bash
uvx xlsx-tools-mcp

uvx fetches and runs the published package without polluting your project. This is the simplest way to power up an MCP client (see configuration snippets below).

2. From source

bash
git clone https://github.com/ruriazz/xlsx-tools-mcp.gitcd xlsx-tools-mcpuv sync# run the server (useful for local dev / debugging):uv run xlsx-tools-mcp

3. Via pip

bash
pip install xlsx-tools-mcp

This installs the console entry point, so you can run the server directly:

bash
xlsx-tools-mcp

Configuration for MCP clients

The simplest registration for every client uses uvx xlsx-tools-mcp (no clone, always the published version).

Tip for Windows: In JSON client configuration files (.mcp.json, opencode.json), use forward slashes (e.g. "C:/path/to/data.xlsx") or escaped backslashes (e.g. "C:\\\\path\\\\to\\\\data.xlsx") to prevent JSON escape sequence errors.

Claude Code

bash
claude mcp add xlsx-tools-mcp -- uvx xlsx-tools-mcp

Or via .mcp.json in your project:

json
{  "mcpServers": {    "xlsx-tools-mcp": { "command": "uvx", "args": ["xlsx-tools-mcp"] }  }}

OpenCode

In opencode.json (project) or ~/.config/opencode/opencode.json (global):

json
{  "mcp": {    "xlsx-tools-mcp": { "type": "local", "command": ["uvx", "xlsx-tools-mcp"], "enabled": true }  }}

When running from a source clone

If you cloned the repo instead of installing from PyPI, point the client at your local checkout by swapping uvx xlsx-tools-mcp for the dynamic uv run form (use the absolute path to the clone):

Claude Code .mcp.json:

json
{  "mcpServers": {    "xlsx-tools-mcp": {      "command": "uv",      "args": ["--directory", "/absolute/path/to/xlsx-reader", "run", "xlsx-tools-mcp"]    }  }}

OpenCode:

json
{  "mcp": {    "xlsx-tools-mcp": {      "type": "local",      "command": ["uv", "--directory", "/absolute/path/to/xlsx-reader", "run", "xlsx-tools-mcp"],      "enabled": true    }  }}

Replace /absolute/path/to/xlsx-reader with the actual location of your clone.


Preloading files (XLSX_MCP_FILES)

Set the XLSX_MCP_FILES environment variable in the MCP server config env section (not your interactive shell — the server is launched by the client) to preload workbooks at startup. Format: comma- or semicolon-separated alias=absolute/path entries, or bare absolute paths:

XLSX_MCP_FILES=name=/abs/path/to/name.xlsx,report=/data/report.xlsx

Bare paths get an alias defaulting to the filename:

XLSX_MCP_FILES=/abs/path/to/sales.xlsx

With alias/filename as the alias:

  • One file configured → every tool can be called with path omitted entirely.
  • Multiple files configured → pass the alias (or filename) as path.
  • list_configured_files() returns the alias → absolute-path mapping.
  • Raw absolute and relative paths still work for files you didn't preload.

Claude Code — .mcp.json with preloading:

json
{  "mcpServers": {    "xlsx-tools-mcp": {      "command": "uvx",      "args": ["xlsx-tools-mcp"],      "env": {        "XLSX_MCP_FILES": "report=/data/report.xlsx,sales=/data/sales.xlsx"      }    }  }}

OpenCode with preloading:

json
{  "mcp": {    "xlsx-tools-mcp": {      "type": "local",      "command": ["uvx", "xlsx-tools-mcp"],      "env": { "XLSX_MCP_FILES": "report=/data/report.xlsx,sales=/data/sales.xlsx" },      "enabled": true    }  }}

Tool reference

All 29 tools. Unless noted, path accepts a filesystem path, a preloaded alias/filename, or may be omitted when exactly one file is preloaded. create_workbook is the exception — its path is required because a new file is never preloaded.

Response shape (all write tools): every write tool returns {"saved": bool, "recalculated": bool, "errors_found": list, "message": str}. When non-empty, errors_found is a list of {"sheet": "...", "cell": "B2", "error": "#DIV/0!"}.

Inspect / Read

ToolDescription
list_configured_files()List files preloaded at startup via XLSX_MCP_FILES, as an alias → absolute-path map. Call this first if unsure what's available.
list_sheets(path?)List every sheet in the workbook with approximate row/column counts (calamine).
get_workbook_info(path?)Workbook-level metadata: per-sheet exact dimensions, max_row/max_column, sheet state, the active sheet, and defined names.
read_sheet(sheet, cell_range?, max_rows?, offset_row?, format?, path?)Read cell values. cell_range limits the reading area. max_rows caps rows. offset_row skips a number of rows for pagination. format can be "array" (2D list), "records" (list of dicts using first row as keys), or "markdown" (table string).
get_cell(sheet, cell, path?)Full detail for a single cell: value (cached computed), formula, number format, font (bold/italic/size/color), fill color, merge state, comment.
search_workbook(query, sheet?, match_case?, limit?, path?)Substring search across one or all sheets. sheet restricts to one sheet; match_case=True makes it case-sensitive; limit caps matches. Returns {"sheet", "cell", "value"}.
aggregate_sheet(sheet, group_by, agg, cell_range?, has_header?, path?)Group and aggregate with pandas. group_by is a list of column names (taken from the header row); agg maps column name → aggregation function, e.g. {"amount": "sum"}. has_header=True (default) reads column names from the first row. Returns {columns, records, row_count}.
profile_sheet(sheet, sample_rows?, path?)Profile sheet metadata: inferred types, null counts, min/max, sample values.
query_sheet(sheet, filter_query, columns?, max_rows?, cell_range?, path?)Filter sheet data using pandas expressions with AST-hardened code injection defense.

Write

ToolDescription
create_workbook(path, sheets?, overwrite?)Create a new .xlsx/.xlsm workbook. sheets defaults to ["Sheet1"]. overwrite=True replaces an existing file. path is required (new files are never preloaded).
write_cells(sheet, cells, create_sheet_if_missing?, recalculate?, allow_external_formulas?, backup?, path?)Write values and/or formulas into specific cells. cells is a list of {"cell": "A1", "value": ...} or {"cell": "B1", "formula": "=A1*2"}. Optionally create the sheet first; recalculate=True (default) runs the LibreOffice recompute.
append_rows(sheet, rows, create_sheet_if_missing?, recalculate?, allow_external_formulas?, backup?, path?)Append rows after the last used row. rows is a list of rows, each a list of cell values in column order.
create_sheet(sheet, index?, path?)Add a new empty sheet. index is a zero-based insert position; omit to append at the end.
delete_sheet(sheet, path?)Delete a sheet. Fails if it's the only sheet left.
rename_sheet(old_name, new_name, path?)Rename an existing sheet.
copy_sheet(source_sheet, target_sheet, path?)Duplicate a sheet including its contents, formulas, and styles.
insert_rows(sheet, start_row, count?, recalculate?, path?)Insert blank rows before start_row (1-based), shifting existing rows down. count defaults to 1.
delete_rows(sheet, start_row, count?, recalculate?, path?)Delete rows starting at start_row (1-based), shifting rows below upward. count defaults to 1.
insert_columns(sheet, start_column, count?, recalculate?, path?)Insert blank columns before start_column (1-based), shifting existing columns right. count defaults to 1.
delete_columns(sheet, start_column, count?, recalculate?, path?)Delete columns starting at start_column (1-based), shifting columns to the right leftward. count defaults to 1.
merge_cells(sheet, cell_range, path?)Merge a rectangular range (e.g. "A1:C1") into one cell.
unmerge_cells(sheet, cell_range, path?)Undo a merge on a previously-merged range.
set_cell_style(sheet, cell_range, style, path?)Apply formatting to a range (e.g. "A1:D1"). style keys: bold, italic, font_size, font_color (hex RGB, e.g. "FF0000"), bg_color (hex RGB), horizontal, vertical (alignment), border ("thin", "medium", "thick", …), number_format (e.g. "#,##0.00").
autofit_columns(sheet, min_width?, max_width?, padding?, path?)Automatically adjust column widths based on maximum text length to prevent clipping.
clear_range(sheet, cell_range, clear_values?, clear_styles?, path?)Clear cell values and/or styles within a specified range without deleting rows or columns.
create_table(sheet, cell_range, table_name, style_name?, show_filter?, show_row_stripes?, path?)Create a formal Excel Table over a range.
create_chart(sheet, chart_type, data_range, categories_range?, title?, target_cell?, path?)Add a native Excel chart (bar, line, pie, scatter).
recalculate_workbook(path?)Force a LibreOffice headless recalculation pass and report any formula errors found.
restore_backup(backup_path, target_path)Restore a .bak backup file over a target workbook atomically.

Example payload — write_cells

A call writing a formula and a value:

json
{  "sheet": "Sheet1",  "cells": [    { "cell": "A1", "value": 100 },    { "cell": "B1", "formula": "=A1*2" }  ],  "recalculate": true,  "path": "/data/budget.xlsx"}

Matching response:

json
{  "saved": true,  "recalculated": true,  "errors_found": [],  "message": "Recalculated with LibreOffice headless."}

If a formula this touches produced an error, errors_found would look like:

json
{  "saved": true,  "recalculated": true,  "errors_found": [    { "sheet": "Sheet1", "cell": "C5", "error": "#DIV/0!" }  ],  "message": "Recalculated with LibreOffice headless."}

Example payload — query_sheet

json
{  "sheet": "Sales",  "filter_query": "Revenue > 500 and Status == 'PAID'",  "columns": ["Customer", "Revenue"],  "max_rows": 10}

Example payload — create_table & create_chart

json
{  "sheet": "Summary",  "cell_range": "A1:D10",  "table_name": "SalesTable",  "style_name": "TableStyleMedium9"}
json
{  "sheet": "Summary",  "chart_type": "bar",  "data_range": "B1:B10",  "categories_range": "A2:A10",  "title": "Monthly Revenue",  "target_cell": "F2"}

Environment variables

VariableDefaultDescription
XLSX_MCP_FILESemptyComma or semicolon-separated alias=path or path to preload at startup.
XLSX_MCP_ALLOWED_DIRSemptyComma or semicolon-separated directories to confine file access (paths outside raise AccessDeniedError). Supports case-insensitivity on Windows.
XLSX_MCP_AUTO_BACKUPtrueAutomatically create a .bak copy before modifying a workbook.
XLSX_MCP_BACKUP_DIRemptyCustom directory for backup files (defaults to beside the target file).
XLSX_MCP_RECALC_TIMEOUT60Timeout in seconds for headless LibreOffice formula recalculation.
XLSX_MCP_LOCK_TIMEOUT10Timeout in seconds to acquire per-file lock before failing.

Security & concurrency

  • Path confinement — XLSX_MCP_ALLOWED_DIRS (comma or semicolon-separated) restricts all reads and writes to specific directories. If set, any attempt to access a file outside these boundaries raises AccessDeniedError. Case-insensitive path comparisons and multi-drive paths on Windows are supported.
  • Auto-backup & restore — Write tools will automatically create a .bak sibling file before modifying the workbook if backup=True (which defaults to XLSX_MCP_AUTO_BACKUP=true). Use XLSX_MCP_BACKUP_DIR to save backups to a specific folder. Use restore_backup to atomically revert changes.
  • Formula injection guard — write_cells and append_rows reject formulas containing WEBSERVICE, HYPERLINK, INDIRECT, RTD, CALL, REGISTER, or DDE commands (|) by default to prevent data exfiltration or command execution. Pass allow_external_formulas=True to bypass this check.
  • AST safe query validation — query_sheet uses an AST parser to strictly allow only comparisons, boolean logic, and safe operators, blocking @ variable lookups, code execution calls, and private dunder attributes.
  • XML-bomb protection — defusedxml is an automatic dependency of this package. openpyxl auto-detects it and uses its hardened XML parser, so a malicious .xlsx (a zip of XML) can't trigger entity-expansion resource exhaustion. No configuration needed.
  • Per-file locking — every read/write acquires a sibling <path>.lock file (via filelock). Concurrent tool calls or other processes touching the same workbook are serialized so writes never interleave and corrupt the file.
  • Transient lock resilience — on Windows NTFS, atomic file swaps can momentarily encounter sharing violations (WinError 32 / 33) while antivirus scanners or search indexers inspect newly saved files. The server performs an exponential backoff retry to transparently succeed once released, or provides a clear guidance message if the file is permanently open in Microsoft Excel.
  • Recalc timeout — XLSX_MCP_RECALC_TIMEOUT (seconds, default 60) caps how long the LibreOffice recalculation pass may run.
  • Lock timeout — XLSX_MCP_LOCK_TIMEOUT (seconds, default 10) caps how long a tool will wait to acquire the per-file lock before failing.

Troubleshooting

  • errors_found is empty even though my formula is broken — recalculation likely didn't run. Check the message field: if it says LibreOffice wasn't found, the file was saved via openpyxl as-is and formulas were not recomputed (cached values may be stale). Install LibreOffice (see Requirements).
  • Recalculation is slow or times out — raise XLSX_MCP_RECALC_TIMEOUT (default 60s). On timeout, the file is still saved, but recalculated will be false and message says the recalc timed out.
  • LockTimeoutError on concurrent access — another operation holds the lock. Raise XLSX_MCP_LOCK_TIMEOUT (default 10s), or retry when the other operation finishes.
  • Workbook is locked by another process / WinError 32 — on Windows, Microsoft Excel and some applications lock open files exclusively. Close the workbook in Excel and retry. Transient locks from antivirus scanners or search indexers are automatically retried by the server before failing.
  • "Sheet not found" — the error message lists the available sheet names, so you can pick the correct one.
  • path required / no file configured — you called a tool without path but no (or multiple) files are preloaded. Preload one file via XLSX_MCP_FILES, pass an explicit alias, or pass a raw path.

Development / Contributing

See CONTRIBUTING.md. Run the test suite with:

bash
uv run pytest

來源:README.md,提交 452c821

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

4
  1. v0.3.2最新Oct 17, 2026
  2. v0.3.1Oct 9, 2026
  3. v0.3.0Oct 3, 2026
  4. v0.1.1Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分