Skip to content

把 Office 文档转成 Markdown

Office Oxide 每个句柄都带 to_markdown(),可以从六种格式中任意一种生成 GitHub Flavored Markdown — 标题、表格、列表、代码风格块。这是绝大多数 LLM 与 RAG 管道首选的入口。

一次性

Rust

use office_oxide::to_markdown;

let md = to_markdown("report.docx")?;
std::fs::write("report.md", md)?;

Python

import office_oxide

md = office_oxide.to_markdown("report.docx")
open("report.md", "w").write(md)

JavaScript

import { toMarkdown } from 'office-oxide';
import { writeFileSync } from 'node:fs';

writeFileSync('report.md', toMarkdown('report.docx'));

Go

md, err := officeoxide.ToMarkdown("report.docx")
os.WriteFile("report.md", []byte(md), 0o644)

C#

File.WriteAllText("report.md", OfficeOxide.ToMarkdown("report.docx"));

复用句柄

Python

from office_oxide import Document

with Document.open("deck.pptx") as doc:
    md = doc.to_markdown()

Rust

let doc = office_oxide::Document::open("deck.pptx")?;
let md = doc.to_markdown();

JavaScript

using doc = Document.open('deck.pptx');
const md = doc.toMarkdown();

实际产出

源元素 Markdown
DOCX 标题(<w:pStyle w:val="Heading1"/> …) # 标题(级别与样式对应)
DOCX 段落 一个段落,去除软连字符
DOCX 列表项 - 项1. 项(保留编号)
DOCX 表格 GFM 管道表
XLSX 工作表 ## 工作表名,每个范围一个管道表
XLSX 合并单元格 取第一格内容,span 丢弃
PPTX 幻灯片 ## 幻灯片 N + 正文,备注作为引用块附加
PPTX 表格 在幻灯片内联出现的 GFM 管道表
超链接 [文本](url)
图片 ![alt](filename) 占位符 — 见下文「图片」

图片

to_markdown() 用文件名占位符表示图片(如 ![](image1.png)),但不抽取图片字节 — Markdown 是文本格式。要获取图片,请用 IR 或按格式访问:

from office_oxide import Document

with Document.open("report.docx") as doc:
    ir = doc.to_ir()
    for section in ir["sections"]:
        for el in section["elements"]:
            if el["kind"] == "Image":
                print(el["filename"], len(el["data"]))

完整 schema 见 IR 提取

使用场景

  • RAG 摄取 — Markdown 是最适合 LLM 的输入格式。每文档一遍,结构确定,没有 HTML 噪声。
  • 文档索引 — 标题自然成为分块边界;表格依然可查询。
  • 迁移 — 把 DOCX 转成 Markdown,喂给静态站点生成器(Hugo、Astro、MkDocs)。
  • 内容比对 — Markdown diff 比 .docx 二进制 diff 友好得多。

性能

to_markdown()plain_text() 同一个数量级 — 中位文档大约是它的 1〜2 倍开销。完整数据见 性能

相关链接