在日常办公或开发中,有时需要将网页(HTML)内容保存为 Word 文档(.doc 或 .docx)。本文将介绍几种简单有效的方法,适用于不同技术水平的用户。
这是最简单的方法,适合普通用户:
适用于内容较少的页面:
开发者可使用以下代码将 HTML 内容导出为 .doc 文件:
<button onclick="exportToWord()">导出为Word</button>
<div id="content">
<h1>示例标题</h1>
<p>这是要导出的内容。</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>
推荐使用专业工具提高兼容性和格式准确性: