Skip to content

将 Office 文档转为 HTML

Office Oxide 的每个句柄都提供 to_html() 方法,能从任意受支持的格式生成干净的语义化 HTML5。适用于浏览器预览、邮件渲染或快速视觉对比。

一次性转换

Rust

use office_oxide::to_html;

let html = to_html("report.docx")?;
std::fs::write("report.html", html)?;

Python

import office_oxide

html = office_oxide.to_html("report.docx")
open("report.html", "w").write(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"));

C

int err = 0;
char *html = office_to_html("report.docx", &err);   /* HTML fragment */
if (html) {
    FILE *f = fopen("report.html", "w");
    fputs(html, f);
    fclose(f);
    office_oxide_free_string(html);
}

可复用句柄

Rust

let doc = office_oxide::Document::open("slides.pptx")?;
let html = doc.to_html();

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();

C

int err = 0;
OfficeDocumentHandle *doc = office_document_open("slides.pptx", &err);
char *html = office_document_to_html(doc, &err);   /* HTML fragment */
if (html) { /* use html */ office_oxide_free_string(html); }
office_document_free(doc);

WASM

import { WasmDocument } from 'office-oxide-wasm';

const data = new Uint8Array(await (await fetch('/slides.pptx')).arrayBuffer());
using doc = new WasmDocument(data, 'pptx');
const html = doc.toHtml();   // HTML fragment

输出内容

HTML 以片段形式输出 — 不含 <html><head><body> 包裹层。挂载位置和所用样式表由你决定。

来源 HTML 元素
标题 <h1><h6>,与源级别对应
段落 <p>
粗体 / 斜体 / 下划线 <strong><em><u>
列表 <ul> / <ol><li> 子节点
表格 <table>,含 <thead><tbody><tr><th><td>
超链接 <a href="...">
图片 <img src="..." alt="...">
XLSX 工作表 <section data-sheet="name"> + <table>
PPTX 幻灯片 <section data-slide="N"> + 正文 + 可选备注 <aside>

输出经过转义处理:文档中的用户内容会被 HTML 转义,因此默认情况下将结果嵌入页面是安全的。

封装为独立页面

Python

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>Report</title>
<link rel="stylesheet" href="docs.css">
</head><body>{body}</body></html>"""

open("report.html", "w").write(page)

使用场景

  • 浏览器内预览用户上传的文档(<input type="file"> → WASM → <iframe srcdoc>
  • 生成报告的邮件渲染
  • 差异视图 — HTML diff 在代码审查工具中具有实际意义
  • 保留文档结构的搜索索引(标题可提升搜索排名)

相关链接