在实际开发中,有时我们需要让用户从网页直接下载 Word 文档。其实只需几行原生 HTML + JavaScript 代码,就能实现这一功能,无需任何第三方库!
通过设置 document 的 MIME 类型为 application/msword,并利用 Blob 和 URL.createObjectURL() 创建可下载链接,即可将 HTML 内容保存为 .doc 文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="exportToWord()">下载Word文档</button>
<script>
function exportToWord() {
const html = `<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>
<h1>这是由HTML生成的Word文档</h1>
<p>内容可以包含文字、列表、表格等基本HTML元素。</p>
</body>
</html>`;
const blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = '文档.doc';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
</script>
</body>
</html>
.doc,可在 Microsoft Word、WPS 等软件中打开;h1、p、ul、table 等),复杂样式可能不生效;docxtemplater 或后端生成。