为什么选择这种方法?
通过简单的 HTML + JavaScript,你可以直接在浏览器中将内容保存为 Word 文档(.doc 格式),适用于快速原型、简易报表、简历生成等场景。
完整示例代码
复制以下代码到你的 HTML 文件中即可使用:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="exportToWord()">导出为Word文档</button>
<div id="content">
<h1>我的Word文档</h1>
<p>这是由HTML生成的内容。</p>
</div>
<script>
function exportToWord() {
const content = document.getElementById('content').innerHTML;
const blob = new Blob(['<html xmlns:o="urn:schemas-microsoft-com:office:office" '
+ 'xmlns:w="urn:schemas-microsoft-com:office:word" '
+ 'xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"></head><body>'
+ content + '</body></html>'],
{ type: 'application/msword' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'document.doc';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
</script>
</body>
</html>
注意事项
- 生成的是 .doc 格式(旧版 Word),非 .docx,但兼容性良好。
- 样式支持有限,建议使用基础 HTML 标签(如 h1, p, table 等)。
- 不适用于复杂排版或图片嵌入(部分浏览器可能限制)。
- 完全在客户端运行,不上传任何数据,安全可靠。