把 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"));
C
int err = 0;
char *md = office_to_markdown("report.docx", &err); /* open + render in one call */
if (md) {
FILE *f = fopen("report.md", "w");
fputs(md, f);
fclose(f);
office_oxide_free_string(md);
}
复用句柄
Rust
let doc = office_oxide::Document::open("deck.pptx")?;
let md = doc.to_markdown();
Python
from office_oxide import Document
with Document.open("deck.pptx") as doc:
md = doc.to_markdown()
JavaScript
using doc = Document.open('deck.pptx');
const md = doc.toMarkdown();
C
int err = 0;
OfficeDocumentHandle *doc = office_document_open("deck.pptx", &err);
if (doc) {
char *md = office_document_to_markdown(doc, &err);
if (md) { /* use md */ office_oxide_free_string(md); }
office_document_free(doc);
}
WASM
import { WasmDocument } from 'office-oxide-wasm';
// WASM has no file I/O — read the bytes yourself, then open from bytes
const data = new Uint8Array(await (await fetch('/deck.pptx')).arrayBuffer());
using doc = new WasmDocument(data, 'pptx');
const md = doc.toMarkdown();
实际产出
| 源元素 | Markdown |
|---|---|
DOCX 标题(<w:pStyle w:val="Heading1"/> …) |
# Heading(级别与样式对应) |
| DOCX 段落 | 一个段落,去除软连字符 |
| DOCX 列表项 | - item 或 1. item(保留编号) |
| DOCX 表格 | GFM 管道表 |
| XLSX 工作表 | ## Sheet name,每个范围一个管道表 |
| XLSX 合并单元格 | 取第一格内容,span 丢弃 |
| PPTX 幻灯片 | ## Slide N + 正文,备注作为引用块附加 |
| PPTX 表格 | 在幻灯片内联出现的 GFM 管道表 |
| 超链接 | [text](url) |
| 图片 |  占位符——见下文「图片」 |
图片
to_markdown() 用文件名占位符表示图片(如 ),但不抽取图片字节——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 倍开销。完整数据见 性能。
相关链接
- HTML 提取 — 需要带样式输出时使用
- IR 提取 — 需要更复杂管道时的结构化 JSON
- PDF for RAG — 处理 PDF 的姊妹库
pdf_oxide