把 Office 文档转成 HTML
Office Oxide 每个句柄都带 to_html(),可以从任何受支持的格式生成干净、语义化的 HTML5。适合浏览器预览、邮件渲染和快速视觉比对。
一次性
Python
import office_oxide
html = office_oxide.to_html("report.docx")
open("report.html", "w").write(html)
Rust
use office_oxide::to_html;
let html = to_html("report.docx")?;
std::fs::write("report.html", html)?;
JavaScript
import { toHtml } from 'office-oxide';
import { writeFileSync } from 'node:fs';
writeFileSync('report.html', toHtml('report.docx'));
Go
html, err := officeoxide.ToHTML("report.docx")
os.WriteFile("report.html", []byte(html), 0o644)
C#
File.WriteAllText("report.html", OfficeOxide.ToHtml("report.docx"));
复用句柄
Python
from office_oxide import Document
with Document.open("slides.pptx") as doc:
html = doc.to_html()
JavaScript
using doc = Document.open('slides.pptx');
const html = doc.toHtml();
Rust
let doc = office_oxide::Document::open("slides.pptx")?;
let html = doc.to_html();
实际产出
输出是 片段(fragment)形式 — 没有 <html>、<head>、<body> 包裹。挂载位置和样式表由你决定。
| 源 | HTML 元素 |
|---|---|
| 标题 | 与源级别对应的 <h1> … <h6> |
| 段落 | <p> |
| 粗体 / 斜体 / 下划线 | <strong>、<em>、<u> |
| 列表 | 带 <li> 子节点的 <ul> / <ol> |
| 表格 | <table> 内含 <thead>、<tbody>、<tr>、<th>、<td> |
| 超链接 | <a href="..."> |
| 图片 | <img src="..." alt="..."> |
| XLSX 工作表 | <section data-sheet="名称"> + <table> |
| PPTX 幻灯片 | <section data-slide="N"> + 正文 + 可选的备注 <aside> |
输出是经过转义的:文档中的用户内容会被 HTML 转义,所以默认情况下把结果嵌进页面是安全的。
包成独立页面
from office_oxide import Document
with Document.open("report.docx") as doc:
body = doc.to_html()
page = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>报告</title>
<link rel="stylesheet" href="docs.css">
</head><body>{body}</body></html>"""
open("report.html", "w").write(page)
使用场景
- 在浏览器中预览 用户上传的文档(
<input type="file">→ WASM →<iframe srcdoc>)。 - 生成报告的 邮件渲染。
- diff 视图 — HTML diff 在代码评审工具里更有意义。
- 保留结构的 搜索索引(让标题影响排序)。
相关链接
- Markdown 提取 — 想要更纯文本的输出时
- IR 提取 — 想自己渲染时使用结构化 JSON
- WASM 快速上手 — 在浏览器中做转换