Vue实现word导出
Vue 实现 Word 导出方法
使用 docx 库生成 Word 文档
安装 docx 库:
npm install docx
创建 Word 文档示例代码:
import { Document, Paragraph, TextRun, Packer } from "docx";
const generateDocx = async () => {
const doc = new Document({
sections: [{
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
],
}],
});
const blob = await Packer.toBlob(doc);
saveAs(blob, "example.docx");
};
使用 html-docx-js 转换 HTML 为 Word
安装 html-docx-js:
npm install html-docx-js
示例代码:
import htmlDocx from 'html-docx-js';
const exportAsWord = () => {
const html = `<h1>标题</h1><p>内容</p>`;
const converted = htmlDocx.asBlob(html);
const url = URL.createObjectURL(converted);
const link = document.createElement('a');
link.href = url;
link.download = 'document.docx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
使用 FileSaver 保存文件
安装 FileSaver:
npm install file-saver
配合 docx 使用:
import { saveAs } from 'file-saver';
// 结合前面 docx 示例使用
// saveAs(blob, "filename.docx");
使用后台服务生成 Word
对于复杂需求可调用后台服务:
axios.post('/api/export-word', { content: htmlContent }, {
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'report.docx');
document.body.appendChild(link);
link.click();
});
使用 vue-html2pdf 和 docx 组合方案
先转 PDF 再转 Word(需后端支持):
npm install vue-html2pdf
示例:

import VueHtml2pdf from 'vue-html2pdf';
export default {
components: { VueHtml2pdf },
methods: {
generatePdf() {
this.$refs.html2Pdf.generatePdf();
}
}
}
注意事项
- 复杂样式在 Word 中可能显示不一致
- 表格和图片需要特殊处理
- 中文需确保字体支持
- 大文件考虑分块处理
以上方案可根据项目需求选择,简单内容推荐前端方案,复杂文档建议使用后端生成。






