Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(source_to_md): add Excel workbook converter

hugohe3fc790017efca
diff --git a/AGENTS.md b/AGENTS.md
index 2a61e9b5..8e3578c0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,6 +33,7 @@ These commands are a convenience summary only. The full step-by-step workflow re
# Source content conversion
python3 skills/ppt-master/scripts/source_to_md/pdf_to_md.py <PDF_file>
python3 skills/ppt-master/scripts/source_to_md/doc_to_md.py <DOCX_or_other_file>
+python3 skills/ppt-master/scripts/source_to_md/excel_to_md.py <XLSX_or_XLSM_file>
python3 skills/ppt-master/scripts/source_to_md/ppt_to_md.py <PPTX_file>
python3 skills/ppt-master/scripts/source_to_md/web_to_md.py <URL>
diff --git a/docs/technical-design.md b/docs/technical-design.md
index 2e47c4c5..ec04ac70 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -15,9 +15,9 @@ The generated PPTX is a **design draft**, not a finished product. Think of it li
## System Architecture
```
-User Input (PDF/DOCX/URL/Markdown)
+User Input (PDF/DOCX/XLSX/URL/Markdown)
↓
-[Source Content Conversion] → source_to_md/pdf_to_md.py / doc_to_md.py / ppt_to_md.py / web_to_md.py
+[Source Content Conversion] → source_to_md/pdf_to_md.py / doc_to_md.py / excel_to_md.py / ppt_to_md.py / web_to_md.py
↓
[Create Project] → project_manager.py init <project_name> --format <format>
↓
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index c1192fa4..82cfa53f 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -15,9 +15,9 @@
## 系统架构
```
-用户输入 (PDF/DOCX/URL/Markdown)
+用户输入 (PDF/DOCX/XLSX/URL/Markdown)
↓
-[源内容转换] → source_to_md/pdf_to_md.py / doc_to_md.py / ppt_to_md.py / web_to_md.py
+[源内容转换] → source_to_md/pdf_to_md.py / doc_to_md.py / excel_to_md.py / ppt_to_md.py / web_to_md.py
↓
[创建项目] → project_manager.py init <项目名> --format <格式>
↓
diff --git a/requirements.txt b/requirements.txt
index 574eaaac..7268947f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -49,6 +49,13 @@ mammoth>=1.6.0
markdownify>=0.11.6
ebooklib>=0.18
nbconvert>=7.0.0
+
+# ─────────────────────────────────────────────────────────────
+# Excel to Markdown tool / Excel 转 Markdown 工具 (skills/ppt-master/scripts/source_to_md/excel_to_md.py)
+# ─────────────────────────────────────────────────────────────
+# Converts .xlsx/.xlsm workbooks to Markdown while preserving sheet structure.
+# 用于将 .xlsx/.xlsm 工作簿转换为 Markdown,并保留工作表结构。
+openpyxl>=3.1.0
#
# Fallback path — only needed for less common formats
# (.doc .odt .rtf .tex/.latex .rst .org .typ).
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index e17cb052..be512ba8 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -47,6 +47,7 @@ description: >
|--------|---------|
| `${SKILL_DIR}/scripts/source_to_md/pdf_to_md.py` | PDF to Markdown |
| `${SKILL_DIR}/scripts/source_to_md/doc_to_md.py` | Documents to Markdown — native Python for DOCX/HTML/EPUB/IPYNB, pandoc fallback for legacy formats (.doc/.odt/.rtf/.tex/.rst/.org/.typ) |
+| `${SKILL_DIR}/scripts/source_to_md/excel_to_md.py` | Excel workbooks to Markdown — supports .xlsx/.xlsm; legacy .xls should be resaved as .xlsx |
| `${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py` | PowerPoint to Markdown |
| `${SKILL_DIR}/scripts/source_to_md/web_to_md.py` | Web page to Markdown |
| `${SKILL_DIR}/scripts/source_to_md/web_to_md.cjs` | Node.js fallback for WeChat / TLS-blocked sites (use only if `curl_cffi` is unavailable; `web_to_md.py` now handles WeChat when `curl_cffi` is installed) |
@@ -89,6 +90,8 @@ When the user provides non-Markdown content, convert immediately:
|---------------|---------|
| PDF file | `python3 ${SKILL_DIR}/scripts/source_to_md/pdf_to_md.py <file>` |
| DOCX / Word / Office document | `python3 ${SKILL_DIR}/scripts/source_to_md/doc_to_md.py <file>` |
+| XLSX / XLSM / Excel workbook | `python3 ${SKILL_DIR}/scripts/source_to_md/excel_to_md.py <file>` |
+| CSV / TSV | Read directly as plain-text table source |
| PPTX / PowerPoint deck | `python3 ${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py <file>` |
| EPUB / HTML / LaTeX / RST / other | `python3 ${SKILL_DIR}/scripts/source_to_md/doc_to_md.py <file>` |
| Web link | `python3 ${SKILL_DIR}/scripts/source_to_md/web_to_md.py <URL>` |
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 09299f76..2cd1d23e 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -5,7 +5,7 @@ This directory contains user-facing scripts for conversion, project setup, SVG p
## Directory Layout
- Top-level `scripts/`: runnable entry scripts
-- `scripts/source_to_md/`: source-document → Markdown converters (`pdf_to_md.py`, `doc_to_md.py`, `ppt_to_md.py`, `web_to_md.py`, `web_to_md.cjs`)
+- `scripts/source_to_md/`: source-document → Markdown converters (`pdf_to_md.py`, `doc_to_md.py`, `excel_to_md.py`, `ppt_to_md.py`, `web_to_md.py`, `web_to_md.cjs`)
- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`
- `scripts/template_import/`: internal PPTX reference-preparation helpers used by `pptx_template_import.py`
- `scripts/svg_finalize/`: internal post-processing helpers used by `finalize_svg.py`
@@ -20,6 +20,7 @@ Typical end-to-end workflow:
python3 scripts/source_to_md/pdf_to_md.py <file.pdf>
# or
python3 scripts/source_to_md/ppt_to_md.py <deck.pptx>
+python3 scripts/source_to_md/excel_to_md.py <workbook.xlsx>
python3 scripts/project_manager.py init <project_name> --format ppt169
python3 scripts/project_manager.py import-sources <project_path> <source_files...> --move
python3 scripts/total_md_split.py <project_path>
@@ -37,7 +38,7 @@ python3 scripts/update_repo.py
| Area | Primary scripts | Documentation |
|------|-----------------|---------------|
-| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `source_to_md/web_to_md.cjs` | [docs/conversion.md](./docs/conversion.md) |
+| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `source_to_md/web_to_md.cjs` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py` | [docs/project.md](./docs/project.md) |
| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
@@ -53,6 +54,7 @@ Conversion:
python3 scripts/source_to_md/pdf_to_md.py <file.pdf>
python3 scripts/source_to_md/ppt_to_md.py <deck.pptx>
python3 scripts/source_to_md/doc_to_md.py <file.docx>
+python3 scripts/source_to_md/excel_to_md.py <workbook.xlsx>
python3 scripts/source_to_md/web_to_md.py <url>
```
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index a7a517a7..da53db87 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -63,6 +63,38 @@ pip install mammoth markdownify ebooklib nbconvert beautifulsoup4
All paths produce the same output convention: `<input>.md` plus a sibling `<input>_files/` directory containing extracted images with relative references.
+## `source_to_md/excel_to_md.py`
+
+Excel workbook converter for presentation source intake.
+
+Supported formats:
+- `.xlsx`
+- `.xlsm`
+
+Unsupported by default:
+- `.xls` — resave as `.xlsx` first
+
+```bash
+python3 scripts/source_to_md/excel_to_md.py report.xlsx
+python3 scripts/source_to_md/excel_to_md.py report.xlsx -o output.md
+python3 scripts/source_to_md/excel_to_md.py report.xlsm --max-rows 200 --max-cols 40
+```
+
+Behavior:
+- preserves workbook and sheet structure in Markdown
+- exports visible sheets only
+- trims empty outer rows and columns
+- propagates merged-cell labels for readable Markdown tables
+- exports formula cells as cached values; it does not recalculate formulas
+
+Dependency:
+
+```bash
+pip install openpyxl
+```
+
+CSV/TSV files are already plain-text table sources and do not require this converter.
+
## `source_to_md/ppt_to_md.py`
Structured PowerPoint-to-Markdown converter for Open XML slide decks.
diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.py
index 4ab37efc..7d7336e3 100644
--- a/skills/ppt-master/scripts/project_manager.py
+++ b/skills/ppt-master/scripts/project_manager.py
@@ -43,8 +43,11 @@ SKILL_DIR = TOOLS_DIR.parent
REPO_ROOT = SKILL_DIR.parent.parent
SOURCE_DIRNAME = "sources"
TEXT_SOURCE_SUFFIXES = {".md", ".markdown", ".txt"}
+TABLE_TEXT_SUFFIXES = {".csv", ".tsv"}
PDF_SUFFIXES = {".pdf"}
PRESENTATION_SUFFIXES = {".pptx", ".pptm", ".ppsx", ".ppsm", ".potx", ".potm"}
+EXCEL_SUFFIXES = {".xlsx", ".xlsm"}
+LEGACY_EXCEL_SUFFIXES = {".xls"}
DOC_SUFFIXES = {
".docx", ".doc", ".odt", ".rtf", # Office documents
".epub", # eBooks
@@ -263,6 +266,17 @@ class ProjectManager:
]
)
+ def _import_excel(self, excel_path: Path, markdown_path: Path) -> None:
+ self._run_tool(
+ [
+ sys.executable,
+ str(TOOLS_DIR / "source_to_md" / "excel_to_md.py"),
+ str(excel_path),
+ "-o",
+ str(markdown_path),
+ ]
+ )
+
def _import_url(self, url: str, markdown_path: Path) -> None:
# Prefer web_to_md.py: it uses curl_cffi internally when available,
# which handles WeChat and other TLS-fingerprint-blocked sites.
@@ -517,6 +531,34 @@ class ProjectManager:
summary["markdown"].append(str(markdown_path))
except Exception as exc: # pragma: no cover - summary path
summary["skipped"].append(f"{item}: presentation conversion failed ({exc})")
+ elif suffix in EXCEL_SUFFIXES:
+ canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"
+ if archived_path.stem in explicit_markdown_stems:
+ summary["notes"].append(
+ f"{item}: skipped Excel auto-conversion because a same-stem Markdown source was provided"
+ )
+ continue
+ if canonical_markdown_path.exists():
+ summary["markdown"].append(str(canonical_markdown_path))
+ summary["notes"].append(
+ f"{item}: skipped Excel auto-conversion because {canonical_markdown_path.name} already exists"
+ )
+ continue
+ markdown_path = canonical_markdown_path
+ try:
+ self._import_excel(archived_path, markdown_path)
+ summary["markdown"].append(str(markdown_path))
+ except Exception as exc: # pragma: no cover - summary path
+ summary["skipped"].append(f"{item}: Excel conversion failed ({exc})")
+ elif suffix in LEGACY_EXCEL_SUFFIXES:
+ summary["notes"].append(
+ f"{item}: archived only; legacy .xls is not converted automatically. "
+ "Resave as .xlsx to generate Markdown."
+ )
+ elif suffix in TABLE_TEXT_SUFFIXES:
+ summary["notes"].append(
+ f"{item}: archived as a plain-text table source; no Markdown conversion needed"
+ )
elif suffix in DOC_SUFFIXES:
canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"
if archived_path.stem in explicit_markdown_stems:
diff --git a/skills/ppt-master/scripts/source_to_md/excel_to_md.py b/skills/ppt-master/scripts/source_to_md/excel_to_md.py
new file mode 100644
index 00000000..31cf09e6
--- /dev/null
+++ b/skills/ppt-master/scripts/source_to_md/excel_to_md.py
@@ -0,0 +1,378 @@
+#!/usr/bin/env python3
+"""
+Excel to Markdown Converter
+
+Supported formats:
+ .xlsx Excel workbook
+ .xlsm Excel macro-enabled workbook
+
+Unsupported by default:
+ .xls Legacy binary Excel format; resave as .xlsx first
+
+All paths produce the same output convention:
+ <input>.md Markdown file
+"""
+
+import argparse
+import re
+import sys
+from datetime import date, datetime, time
+from pathlib import Path
+from typing import Any
+
+
+# ─────────────────────────────────────────────────────────────
+# Format registry
+# ─────────────────────────────────────────────────────────────
+
+EXCEL_FORMATS = {".xlsx", ".xlsm"}
+LEGACY_EXCEL_FORMATS = {".xls"}
+
+
+# ─────────────────────────────────────────────────────────────
+# Shared helpers
+# ─────────────────────────────────────────────────────────────
+
+def _format_size(size: int) -> str:
+ for unit in ("B", "KB", "MB"):
+ if size < 1024:
+ return f"{size:.0f} {unit}"
+ size /= 1024
+ return f"{size:.1f} GB"
+
+
+def _report_result(out_file: Path) -> None:
+ size = out_file.stat().st_size
+ print(f"[OK] Saved Markdown to: {out_file} ({_format_size(size)})")
+
+
+def _is_empty(value: Any) -> bool:
+ return value is None or (isinstance(value, str) and value.strip() == "")
+
+
+def _markdown_escape(value: str) -> str:
+ value = value.replace("\\", "\\\\")
+ value = value.replace("|", "\\|")
+ value = value.replace("\r\n", "\n").replace("\r", "\n")
+ return re.sub(r"\s*\n\s*", "<br>", value).strip()
+
+
+def _format_cell_value(value: Any) -> str:
+ if _is_empty(value):
+ return ""
+ if isinstance(value, bool):
+ return "TRUE" if value else "FALSE"
+ if isinstance(value, datetime):
+ return value.isoformat(sep=" ", timespec="seconds")
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, time):
+ return value.isoformat(timespec="seconds")
+ if isinstance(value, float):
+ return _markdown_escape(f"{value:g}")
+ return _markdown_escape(str(value))
+
+
+def _is_numeric_value(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _sheet_state_label(sheet_state: str) -> str:
+ if sheet_state == "visible":
+ return "visible"
+ return sheet_state or "unknown"
+
+
+# ─────────────────────────────────────────────────────────────
+# Worksheet extraction
+# ─────────────────────────────────────────────────────────────
+
+def _merged_value_map(worksheet) -> dict[tuple[int, int], Any]:
+ """Return propagated values for merged cells, keyed by (row, column).
+
+ Merged regions whose top-left cell is empty are intentionally skipped.
+ These are typically formatting-only ranges that carry no textual content.
+ """
+ merged_values: dict[tuple[int, int], Any] = {}
+ for merged_range in worksheet.merged_cells.ranges:
+ value = worksheet.cell(merged_range.min_row, merged_range.min_col).value
+ if _is_empty(value):
+ continue
+ for row in range(merged_range.min_row, merged_range.max_row + 1):
+ for col in range(merged_range.min_col, merged_range.max_col + 1):
+ merged_values[(row, col)] = value
+ return merged_values
+
+
+def _cell_value(worksheet, row: int, col: int, merged_values: dict[tuple[int, int], Any]) -> Any:
+ value = worksheet.cell(row, col).value
+ if _is_empty(value):
+ return merged_values.get((row, col), value)
+ return value
+
+
+def _content_bounds(worksheet, merged_values: dict[tuple[int, int], Any]) -> tuple[int, int, int, int] | None:
+ min_row = min_col = None
+ max_row = max_col = None
+
+ for row in worksheet.iter_rows():
+ for cell in row:
+ if _is_empty(cell.value):
+ continue
+ min_row = cell.row if min_row is None else min(min_row, cell.row)
+ max_row = cell.row if max_row is None else max(max_row, cell.row)
+ min_col = cell.column if min_col is None else min(min_col, cell.column)
+ max_col = cell.column if max_col is None else max(max_col, cell.column)
+
+ for row, col in merged_values:
+ min_row = row if min_row is None else min(min_row, row)
+ max_row = row if max_row is None else max(max_row, row)
+ min_col = col if min_col is None else min(min_col, col)
+ max_col = col if max_col is None else max(max_col, col)
+
+ if min_row is None or min_col is None or max_row is None or max_col is None:
+ return None
+ return min_row, min_col, max_row, max_col
+
+
+def _trim_trailing_empty_cells(row: list[Any]) -> list[Any]:
+ trimmed = list(row)
+ while trimmed and _is_empty(trimmed[-1]):
+ trimmed.pop()
+ return trimmed
+
+
+def _extract_rows(
+ worksheet,
+ bounds: tuple[int, int, int, int],
+ merged_values: dict[tuple[int, int], Any],
+ max_rows: int,
+ max_cols: int,
+) -> tuple[list[list[Any]], bool, bool]:
+ min_row, min_col, max_row, max_col = bounds
+
+ row_limit = max_row
+ col_limit = max_col
+ rows_truncated = False
+ cols_truncated = False
+
+ if max_rows > 0 and (max_row - min_row + 1) > max_rows:
+ row_limit = min_row + max_rows - 1
+ rows_truncated = True
+ if max_cols > 0 and (max_col - min_col + 1) > max_cols:
+ col_limit = min_col + max_cols - 1
+ cols_truncated = True
+
+ rows: list[list[Any]] = []
+ width = 0
+ for row_index in range(min_row, row_limit + 1):
+ row = [
+ _cell_value(worksheet, row_index, col_index, merged_values)
+ for col_index in range(min_col, col_limit + 1)
+ ]
+ row = _trim_trailing_empty_cells(row)
+ width = max(width, len(row))
+ rows.append(row)
+
+ if width == 0:
+ return [], rows_truncated, cols_truncated
+
+ normalized_rows = [row + [""] * (width - len(row)) for row in rows]
+ return normalized_rows, rows_truncated, cols_truncated
+
+
+def _column_alignments(rows: list[list[Any]]) -> list[str]:
+ if not rows:
+ return []
+
+ width = len(rows[0])
+ alignments: list[str] = []
+ data_rows = rows[1:] if len(rows) > 1 else rows
+ for col_index in range(width):
+ values = [row[col_index] for row in data_rows if not _is_empty(row[col_index])]
+ if values and all(_is_numeric_value(value) for value in values):
+ alignments.append("---:")
+ else:
+ alignments.append("---")
+ return alignments
+
+
+def _rows_to_markdown_table(rows: list[list[Any]]) -> str:
+ if not rows:
+ return "_No tabular content found._"
+
+ formatted_rows = [[_format_cell_value(value) for value in row] for row in rows]
+ width = len(formatted_rows[0])
+ separator = _column_alignments(rows)
+ lines = [
+ "| " + " | ".join(formatted_rows[0]) + " |",
+ "| " + " | ".join(separator or ["---"] * width) + " |",
+ ]
+
+ for row in formatted_rows[1:]:
+ lines.append("| " + " | ".join(row) + " |")
+
+ return "\n".join(lines)
+
+
+# ─────────────────────────────────────────────────────────────
+# Excel → Markdown
+# ─────────────────────────────────────────────────────────────
+
+def _convert_excel(input_file: Path, out_file: Path, max_rows: int, max_cols: int) -> str:
+ try:
+ from openpyxl import load_workbook
+ from openpyxl.utils import get_column_letter
+ except ImportError:
+ print("[ERROR] openpyxl not installed. Run: pip install openpyxl")
+ return ""
+
+ workbook = load_workbook(input_file, data_only=True, read_only=False)
+ visible_sheets = [sheet for sheet in workbook.worksheets if sheet.sheet_state == "visible"]
+
+ lines: list[str] = [
+ f"# Spreadsheet Source: {input_file.name}",
+ "",
+ "## Workbook Summary",
+ "",
+ f"- Sheets: {len(workbook.worksheets)}",
+ f"- Visible sheets: {', '.join(sheet.title for sheet in visible_sheets) or 'None'}",
+ "",
+ "> Note: Formula cells are exported as cached values. This converter does not recalculate formulas.",
+ "",
+ ]
+
+ if not visible_sheets:
+ lines.extend(["_No visible sheets found._", ""])
+
+ for worksheet in visible_sheets:
+ merged_values = _merged_value_map(worksheet)
+ bounds = _content_bounds(worksheet, merged_values)
+
+ lines.extend([
+ f"## Sheet: {worksheet.title}",
+ "",
+ f"- State: {_sheet_state_label(worksheet.sheet_state)}",
+ ])
+
+ if bounds is None:
+ lines.extend(["", "_No content found._", ""])
+ continue
+
+ min_row, min_col, max_row, max_col = bounds
+ used_range = (
+ f"{get_column_letter(min_col)}{min_row}:"
+ f"{get_column_letter(max_col)}{max_row}"
+ )
+ rows, rows_truncated, cols_truncated = _extract_rows(
+ worksheet,
+ bounds,
+ merged_values,
+ max_rows=max_rows,
+ max_cols=max_cols,
+ )
+
+ lines.extend([
+ f"- Used range: {used_range}",
+ f"- Rows: {max_row - min_row + 1}",
+ f"- Columns: {max_col - min_col + 1}",
+ "",
+ ])
+
+ if rows_truncated or cols_truncated:
+ limit_notes = []
+ if rows_truncated:
+ limit_notes.append(f"rows limited to {max_rows}")
+ if cols_truncated:
+ limit_notes.append(f"columns limited to {max_cols}")
+ lines.extend([f"> Truncated: {', '.join(limit_notes)}.", ""])
+
+ lines.extend([_rows_to_markdown_table(rows), ""])
+
+ markdown = "\n".join(lines).rstrip() + "\n"
+ out_file.write_text(markdown, encoding="utf-8")
+ _report_result(out_file)
+ return markdown
+
+
+# ─────────────────────────────────────────────────────────────
+# Dispatcher
+# ─────────────────────────────────────────────────────────────
+
+def convert_to_markdown(
+ input_path: str,
+ output_path: str | None = None,
+ max_rows: int = 0,
+ max_cols: int = 0,
+) -> str:
+ input_file = Path(input_path)
+ if not input_file.exists():
+ print(f"[ERROR] File not found: {input_path}")
+ return ""
+
+ suffix = input_file.suffix.lower()
+ if suffix in LEGACY_EXCEL_FORMATS:
+ print("[ERROR] Unsupported legacy Excel format: .xls")
+ print(" Please resave the workbook as .xlsx and run this converter again.")
+ return ""
+ if suffix not in EXCEL_FORMATS:
+ supported = ", ".join(sorted(EXCEL_FORMATS))
+ print(f"[ERROR] Unsupported format: {suffix}")
+ print(f" Supported: {supported}")
+ return ""
+
+ if max_rows < 0 or max_cols < 0:
+ print("[ERROR] --max-rows and --max-cols must be zero or positive integers")
+ return ""
+
+ out_file = Path(output_path) if output_path else input_file.with_suffix(".md")
+ out_file.parent.mkdir(parents=True, exist_ok=True)
+
+ print(f"[INFO] Converting Excel workbook: {input_file.name}")
+ return _convert_excel(input_file, out_file, max_rows=max_rows, max_cols=max_cols)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ description="Convert Excel workbooks to Markdown",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python excel_to_md.py report.xlsx
+ python excel_to_md.py report.xlsx -o output.md
+ python excel_to_md.py report.xlsm --max-rows 200 --max-cols 40
+
+Supported formats:
+ .xlsx .xlsm
+
+Unsupported by default:
+ .xls Resave as .xlsx first
+ """,
+ )
+ parser.add_argument("input", help="Input Excel workbook")
+ parser.add_argument("-o", "--output", help="Output Markdown file path")
+ parser.add_argument(
+ "--max-rows",
+ type=int,
+ default=0,
+ help="Maximum rows per sheet to export (0 = no limit)",
+ )
+ parser.add_argument(
+ "--max-cols",
+ type=int,
+ default=0,
+ help="Maximum columns per sheet to export (0 = no limit)",
+ )
+ args = parser.parse_args()
+
+ result = convert_to_markdown(
+ args.input,
+ args.output,
+ max_rows=args.max_rows,
+ max_cols=args.max_cols,
+ )
+ sys.exit(0 if result else 1)
+
+
+if __name__ == "__main__":
+ main()