Generated banner for Convert Excel To Md
Generated logo for Convert Excel To Md

Convert Excel To Md

GitHubOfficialFirst committed by 1YaoWei0Distributed by GitHub

  • Skill
  • Tool integration
  • Automation and integrations
  • MIT
  • Low risk
  • Has scripts

From the author

Converts Excel (.xlsx) workbooks into Markdown so their contents can be accurately analyzed, summarized, searched, or extracted from. Use this skill whenever the user shares, references, or asks about a .xlsx file — even if they don't say "convert" or "markdown" explicitly. This includes requests to "read", "summarize", "review", "extract data from", "compare", "chart", or "analyze" a spreadsheet, workbook, budget, data export, or tracker. Always run the bundled conversion script to produce Markdown first; do not attempt to parse .xlsx content directly or write ad-hoc extraction code. Also use this skill for batch requests involving a whole folder of Excel workbooks. IMPORTANT: When the user references a folder or set of documents containing multiple file types (.pdf, .docx, .xlsx), invoke ALL three sibling skills — convert-pdf-to-md, convert-word-to-md, and convert-excel-to-md — so no file type is silently skipped.
— the description by 1YaoWei0

AutoGineer summary

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

This skill provides a mechanism to convert Excel .xlsx files into Markdown format, enabling agents to read, summarize, and extract data from spreadsheets. It handles individual files or batch processing of folders, including the extraction of embedded raster images into a structured output folder. The skill is designed to be used as a prerequisite for any task requiring the interpretation of Excel data, ensuring the content is in a readable text-based format.

What it does

  • Converts .xlsx workbooks into Markdown tables
  • Extracts embedded raster images from spreadsheets into a dedicated folder
  • Supports batch processing of entire folders of Excel files
  • Provides recursive folder processing options
  • Integrates with sibling skills for handling mixed-format document sets

When to use it

  • When a user asks to read, summarize, or analyze an .xlsx file
  • When extracting specific data points or rows from a spreadsheet
  • When processing folders containing multiple Excel workbooks
  • When handling mixed document sets containing .pdf, .docx, and .xlsx files

Advantages

  • Enables text-based analysis of complex spreadsheet data
  • Maintains context by organizing extracted images alongside sheet data
  • Supports automated batch workflows for multiple files
  • Provides a consistent output structure for downstream tasks

Usage examples

“Can you summarize the budget in this spreadsheet?”
The agent invokes the conversion script to generate Markdown, then reads the resulting file to provide a summary.
“Extract the sales figures from all files in this folder.”
The agent runs the conversion script in batch mode on the specified folder and parses the generated Markdown to extract the requested figures.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/github/convert-excel-to-md/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip convert-excel-to-md.zip -d .agents/skills

Documentation by 1YaoWei0

Convert Excel to Markdown

When to use this skill

Trigger this skill any time there is a .xlsx file that needs to be understood or processed — for example, a user attaches a spreadsheet and asks questions about it, wants a summary of the data, wants specific rows or values pulled out, or wants multiple workbooks in a folder processed together. Excel's native .xlsx format is a zipped XML bundle that is not reliably readable as plain text, so always convert it to Markdown first using the script in this skill rather than trying to open or parse the file directly.

This skill only supports .xlsx. If asked to convert a legacy .xls file, tell the user it isn't supported and ask them to re-save it as .xlsx (Excel: File > Save As > Excel Workbook (.xlsx)) first.

Mixed file types: When the user references a folder or set of documents containing multiple supported file types (.pdf, .docx, .xlsx), this skill handles only .xlsx files. The agent MUST also invoke the sibling skills in parallel:

  • convert-pdf-to-md for any .pdf files

  • convert-word-to-md for any .docx files

Never process a folder and silently skip a supported file type. All three skills must be invoked together when mixed types are present.

Setup (once per environment)

Before the first conversion in a given environment, follow references/setup.md step by step to ensure Python, pip, and the markitdown package are installed. Do this proactively rather than guessing whether the environment is ready — the script itself will also fail with a clear pointer back to that file if markitdown turns out to be missing, so it's safe to just try the conversion first if you're reasonably confident setup was already done.

Usage

The conversion script lives at scripts/convert_excel_to_md.py.

Output structure: MarkItDown's XLSX converter renders each sheet as its own ## <SheetName> Markdown table — it has no support for embedded images at all. This script separately extracts real embedded images (raster pictures, not charts) and maps them to the sheet they belong to, writing a self-contained folder per document:

<name>/
    img/
        sheet001_<sheetname>_img001.<ext>
        sheet002_<sheetname>_img001.<ext>
        ...
    <name>.md          (each sheet's images appear right after its table,
                         under a "#### Images in this sheet" heading)

This is per-sheet placement, not exact cell position — the finest granularity MarkItDown's stable output anchors (the ## <SheetName> headings) allow. If a workbook has no embedded images, no img/ folder or image sections are created. Native Excel charts are not extracted as images (only actual embedded pictures are — charts would need to be rendered by Excel/LibreOffice, which this lightweight skill does not do).

Single file:

python scripts\convert_excel_to_md.py "C:\path\to\workbook.xlsx"

This creates a workbook\ folder next to the source file (containing workbook.md and, if present, workbook\img\). To control the destination folder explicitly:

python scripts\convert_excel_to_md.py "C:\path\to\workbook.xlsx" -o "C:\path\to\output_folder"

A folder of workbooks (batch mode):

python scripts\convert_excel_to_md.py "C:\path\to\folder"

Add --recursive to also include subfolders:

python scripts\convert_excel_to_md.py "C:\path\to\folder" --recursive

Each .xlsx found gets its own <name>\ output folder next to it by default. Pass -o "C:\path\to\output_parent" to collect all the generated <name>\ folders under a separate parent directory instead (subfolder structure is preserved when combined with --recursive).

After conversion, read the resulting .md file(s) to perform the actual analysis the user asked for — the script's job is only to produce accurate Markdown (and images), not to interpret the content.

Deciding where output goes

Default — always output next to the source file. The <name>/ folder is created in the same directory as the source .xlsx. This is the required default for every case. Do NOT override it unless the user explicitly asks for a different location.

Only use -o when the user explicitly provides an output path (e.g., "save the output to C:\output", "put the results in D:\work"). Do NOT pass -o based on the agent's current working directory, the session state folder, or any implied location.

If the source file path cannot be fully resolved — for example, the user provides only a filename with no directory, or the path is ambiguous — use ask_user to confirm the full absolute path before running the conversion. Never guess or assume the directory.

Troubleshooting

SymptomLikely causeFix
ModuleNotFoundError: No module named 'markitdown' / exit code 2MarkItDown not installedFollow references/setup.md
ERROR: Unsupported file type '.xls' / exit code 3Legacy .xls, not .xlsxAsk the user to re-save as .xlsx
ERROR: Input path not found / exit code 3Wrong path, or file movedConfirm the correct path with the user
FAILED <file> -> ... in batch outputThat specific file is corrupt, password-protected, or otherwise unreadableReport which file(s) failed; other files in the batch still succeed
NOTE: skipped N non-.xlsx file(s)Folder contains non-Excel filesExpected — those files are intentionally ignored
A sheet's charts don't appear as imagesCharts are chart objects, not embedded pictures — this skill only extracts real embedded raster imagesExpected; mention this limitation if the user specifically needs chart images

Files

scripts/convert_excel_to_md.py

#!/usr/bin/env python3
"""Convert Excel (.xlsx) workbooks to Markdown using Microsoft's MarkItDown,
with embedded images extracted to real files and placed under the correct
sheet (MarkItDown's XLSX converter only extracts sheet data as tables -- it
has no support for embedded images at all).

Usage:
    python convert_excel_to_md.py <input> [-o OUTPUT] [--recursive]

<input> may be either:
  - a path to a single .xlsx file, or
  - a path to a directory (batch mode: every .xlsx file directly inside it
    is converted; pass --recursive to also descend into subdirectories).

Output:
  For each source .xlsx (named "<name>.xlsx"), a folder is created
  containing the Markdown and its images, in this layout:

      <name>/
          img/
              Sheet1_img001.<ext>
              Sheet2_img001.<ext>
              ...
          <name>.md

  MarkItDown renders each sheet as its own "## <SheetName>" section with a
  Markdown table. This script independently maps embedded images to the
  sheet they belong to (via the .xlsx zip's drawing relationships) and
  inserts a "#### Images in this sheet" block right after that sheet's
  table, before the next "## " heading. This is per-sheet placement (not
  exact cell position), which is the finest granularity MarkItDown's stable
  output anchors allow.

  - Single file mode: the "<name>/" folder is created next to the source
    file, or at -o/--output (treated as the exact destination folder) if
    given.
  - Batch/directory mode: a "<name>/" folder is created next to each source
    file, or under -o/--output (treated as a parent directory, created if
    missing) if given, preserving relative subfolder structure when
    --recursive is used.
  - If a workbook has no embedded images, no "img/" folder or "Images in
    this sheet" sections are created.

Exit codes:
  0 - all requested conversions succeeded
  1 - one or more conversions failed (partial success in batch mode)
  2 - required dependency ("markitdown") is not installed
  3 - invalid input (path not found, or single-file input is not .xlsx)
"""
import argparse
import posixpath
import re
import shutil
import sys
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET

EXIT_OK = 0
EXIT_CONVERSION_FAILED = 1
EXIT_MISSING_DEPENDENCY = 2
EXIT_INVALID_INPUT = 3

_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
_MAIN_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
_R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
_A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"

# Matches MarkItDown's per-sheet heading, e.g. "## Sheet1"
_SHEET_HEADER_RE = re.compile(r"^## (.+)$", re.MULTILINE)


def _import_markitdown():
    """Import MarkItDown, failing with a clear, actionable message if absent."""
    try:
        from markitdown import MarkItDown
        return MarkItDown
    except ImportError:
        print(
            "ERROR: The 'markitdown' package is not installed.\n"
            "See references/setup.md for this skill, or run:\n"
            '    pip install "markitdown[xlsx]"',
            file=sys.stderr,
        )
        sys.exit(EXIT_MISSING_DEPENDENCY)


def _normalize_rel_path(base_dir: str, target: str) -> str:
    """Resolve a (possibly relative, e.g. '../media/image1.png') relationship
    target against the directory containing the part that referenced it."""
    if target.startswith("/"):
        return target.lstrip("/")
    return posixpath.normpath(posixpath.join(base_dir, target))


def _sheet_name_to_media(xlsx_path: Path):
    """Return {sheet_name: [media_zip_path, ...]} in per-sheet document
    order, by walking workbook.xml -> worksheet -> drawing -> media
    relationships. Returns {} if anything is missing/malformed (falls back
    gracefully -- images just won't be extracted for that sheet)."""
    try:
        with zipfile.ZipFile(xlsx_path) as z:
            names = set(z.namelist())
            if "xl/workbook.xml" not in names or "xl/_rels/workbook.xml.rels" not in names:
                return {}
            workbook_xml = z.read("xl/workbook.xml")
            workbook_rels_xml = z.read("xl/_rels/workbook.xml.rels")

            sheet_rid = {}
            for sheet_el in ET.fromstring(workbook_xml).iter(f"{{{_MAIN_NS}}}sheet"):
                name = sheet_el.get("name")
                rid = sheet_el.get(f"{{{_R_NS}}}id")
                if name and rid:
                    sheet_rid[name] = rid

            rid_target = {}
            for rel in ET.fromstring(workbook_rels_xml).findall(f"{{{_REL_NS}}}Relationship"):
                rid_target[rel.get("Id")] = rel.get("Target")

            result = {}
            for sheet_name, rid in sheet_rid.items():
                target = rid_target.get(rid)
                if not target:
                    continue
                # workbook.xml.rels targets are typically relative to "xl/",
                # but OOXML allows package-absolute targets (leading "/") too.
                sheet_path = _normalize_rel_path("xl", target)
                if sheet_path not in names or "/" not in sheet_path:
                    continue
                sheet_dir, sheet_file = sheet_path.rsplit("/", 1)
                sheet_rels_path = f"{sheet_dir}/_rels/{sheet_file}.rels"
                if sheet_rels_path not in names:
                    continue

                drawing_rid = None
                for d in ET.fromstring(z.read(sheet_path)).iter(f"{{{_MAIN_NS}}}drawing"):
                    drawing_rid = d.get(f"{{{_R_NS}}}id")
                    break
                if not drawing_rid:
                    continue

                drawing_target = None
                for rel in ET.fromstring(z.read(sheet_rels_path)).findall(f"{{{_REL_NS}}}Relationship"):
                    if rel.get("Id") == drawing_rid:
                        drawing_target = rel.get("Target")
                        break
                if not drawing_target:
                    continue
                drawing_path = _normalize_rel_path(sheet_dir, drawing_target)
                if drawing_path not in names or "/" not in drawing_path:
                    continue
                drawing_dir, drawing_file = drawing_path.rsplit("/", 1)
                drawing_rels_path = f"{drawing_dir}/_rels/{drawing_file}.rels"
                if drawing_rels_path not in names:
                    continue

                drawing_rel_map = {}
                for rel in ET.fromstring(z.read(drawing_rels_path)).findall(f"{{{_REL_NS}}}Relationship"):
                    drawing_rel_map[rel.get("Id")] = rel.get("Target")

                media_paths = []
                for blip in ET.fromstring(z.read(drawing_path)).iter(f"{{{_A_NS}}}blip"):
                    embed_rid = blip.get(f"{{{_R_NS}}}embed")
                    if not embed_rid:
                        continue
                    rel_target = drawing_rel_map.get(embed_rid)
                    if not rel_target:
                        continue
                    media_path = _normalize_rel_path(drawing_dir, rel_target)
                    if media_path in names:
                        media_paths.append(media_path)

                if media_paths:
                    result[sheet_name] = media_paths
            return result
    except (zipfile.BadZipFile, KeyError, OSError, ET.ParseError):
        return {}


def _sanitize_filename_part(name: str) -> str:
    safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", name).strip("_")
    return safe or "sheet"


def extract_images(xlsx_path: Path, img_dir: Path):
    """Extract embedded images from xlsx_path, grouped by sheet name.
    Returns {sheet_name: [filename, ...]} in per-sheet order. Files are
    named '<sanitized_sheet_name>_img{N:03d}.<ext>'."""
    sheet_media = _sheet_name_to_media(xlsx_path)
    if not sheet_media:
        return {}

    written = {}
    with zipfile.ZipFile(xlsx_path) as z:
        names_in_zip = set(z.namelist())
        for sheet_idx, (sheet_name, media_paths) in enumerate(sheet_media.items(), start=1):
            safe_name = f"sheet{sheet_idx:03d}_{_sanitize_filename_part(sheet_name)}"
            files = []
            for idx, media_path in enumerate(media_paths, start=1):
                if media_path not in names_in_zip:
                    print(f"WARNING: {media_path} not found in {xlsx_path}", file=sys.stderr)
                    continue
                ext = Path(media_path).suffix.lstrip(".").lower() or "bin"
                if ext == "jpg":
                    ext = "jpeg"
                out_name = f"{safe_name}_img{idx:03d}.{ext}"
                img_dir.mkdir(parents=True, exist_ok=True)
                (img_dir / out_name).write_bytes(z.read(media_path))
                files.append(out_name)
            if files:
                written[sheet_name] = files
    return written


def insert_sheet_images(markdown_text: str, sheet_images) -> str:
    """Insert a '#### Images in this sheet' block right after each sheet's
    section (before the next '## ' heading or end of text). If a sheet has
    no images, or no '## ' headings are found at all, the text is returned
    unchanged for that part."""
    if not sheet_images:
        return markdown_text
    matches = list(_SHEET_HEADER_RE.finditer(markdown_text))
    if not matches:
        return markdown_text

    pieces = []
    last_end = 0
    for i, m in enumerate(matches):
        sheet_name = m.group(1).removesuffix("\r")
        start = m.start()
        end = matches[i + 1].start() if i + 1 < len(matches) else len(markdown_text)
        pieces.append(markdown_text[last_end:start])
        section = markdown_text[start:end].rstrip("\n")
        images = sheet_images.get(sheet_name)
        if images:
            section += "\n\n#### Images in this sheet\n\n"
            section += "\n".join(f"![{name}](img/{name})" for name in images)
        pieces.append(section + "\n\n")
        last_end = end
    pieces.append(markdown_text[last_end:])
    return "".join(pieces).rstrip() + "\n"


def convert_one(md, source: Path, dest_dir: Path) -> bool:
    """Convert a single .xlsx file to a '<name>/' folder containing the
    Markdown file and an 'img/' folder of extracted images. Returns True on
    success."""
    try:
        result = md.convert(str(source))
    except Exception as exc:  # noqa: BLE001 - surface any conversion error
        print(f"FAILED  {source} -> {exc}", file=sys.stderr)
        return False

    try:
        img_dir = dest_dir / "img"
        if dest_dir.exists():
            if img_dir.exists():
              shutil.rmtree(img_dir)
        dest_dir.mkdir(parents=True, exist_ok=True)
        sheet_images = extract_images(source, img_dir)
        text = insert_sheet_images(result.text_content, sheet_images)
        md_path = dest_dir / f"{source.stem}.md"
        md_path.write_text(text, encoding="utf-8")
    except OSError as exc:
        print(f"FAILED  {source} -> could not write output in {dest_dir}: {exc}", file=sys.stderr)
        return False

    img_count = sum(len(v) for v in sheet_images.values())
    img_note = f", {img_count} image(s)" if img_count else ""
    print(f"OK      {source} -> {md_path}{img_note}")
    return True


def find_xlsx_files(root: Path, recursive: bool):
    """Return (xlsx_files, skipped_count) for files directly/recursively under root."""
    pattern_iter = root.rglob("*") if recursive else root.iterdir()
    xlsx_files = []
    skipped = 0
    for entry in pattern_iter:
        if entry.is_dir():
            continue
        if entry.suffix.lower() == ".xlsx":
            xlsx_files.append(entry)
        else:
            skipped += 1
    return sorted(xlsx_files), skipped


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("input", help="Path to a .xlsx file or a directory of .xlsx files")
    parser.add_argument(
        "-o", "--output",
        help=(
            "Destination folder for the '<name>/' output (single-file mode), "
            "or parent directory under which each '<name>/' output folder is "
            "created (batch mode)"
        ),
    )
    parser.add_argument(
        "--recursive", action="store_true",
        help="When input is a directory, also search subdirectories",
    )
    args = parser.parse_args()

    #MarkItDown = _import_markitdown()
    #md = MarkItDown()

    source = Path(args.input)
    if not source.exists():
        print(f"ERROR: Input path not found: {source}", file=sys.stderr)
        return EXIT_INVALID_INPUT

    if source.is_file() and source.suffix.lower() != ".xlsx":
         print(
             f"ERROR: Unsupported file type '{source.suffix}'. "
             "This skill only converts .xlsx files.",
             file=sys.stderr,
         )
         return EXIT_INVALID_INPUT

    MarkItDown = _import_markitdown()
    md = MarkItDown()

    if source.is_file():
        dest_dir = Path(args.output) if args.output else source.parent / source.stem
        return EXIT_OK if convert_one(md, source, dest_dir) else EXIT_CONVERSION_FAILED

    # Directory / batch mode
    xlsx_files, skipped = find_xlsx_files(source, args.recursive)
    if skipped:
        print(f"NOTE: skipped {skipped} non-.xlsx file(s) in {source}")
    if not xlsx_files:
        print(f"ERROR: No .xlsx files found under {source}", file=sys.stderr)
        return EXIT_INVALID_INPUT

    out_dir = Path(args.output) if args.output else None
    success_count = 0
    for xlsx_path in xlsx_files:
        if out_dir is not None:
            rel = xlsx_path.relative_to(source)
            dest_dir = out_dir / rel.parent / xlsx_path.stem
        else:
            dest_dir = xlsx_path.parent / xlsx_path.stem
        if convert_one(md, xlsx_path, dest_dir):
            success_count += 1

    total = len(xlsx_files)
    print(f"\nConverted {success_count}/{total} file(s).")
    return EXIT_OK if success_count == total else EXIT_CONVERSION_FAILED


if __name__ == "__main__":
    sys.exit(main())

Requirements and compatibility

Written for: GitHub Copilot

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

First committed by
GitHub avatar of 1YaoWei01YaoWei0
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/convert-excel-to-md · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
1YaoWei0

AutoGineer is not affiliated with or endorsed by 1YaoWei0 or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download convert-excel-to-md.zip