vue实现生成word
Vue 中实现生成 Word 文档的方法
使用 docx 库生成 Word 文档
安装 docx 库:
npm install docx
创建一个 Vue 组件或方法,使用 docx 生成 Word 文档:
import { Document, Paragraph, TextRun, Packer } from 'docx';
export default {
methods: {
generateWord() {
const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
children: [
new TextRun({
text: 'Hello World',
bold: true,
}),
],
}),
],
}],
});
Packer.toBlob(doc).then((blob) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'example.docx';
link.click();
URL.revokeObjectURL(link.href);
});
},
},
};
使用 html-docx-js 库将 HTML 转换为 Word
安装 html-docx-js 库:

npm install html-docx-js
在 Vue 组件中使用:
import htmlDocx from 'html-docx-js/dist/html-docx';
export default {
methods: {
generateWordFromHTML() {
const html = '<h1>Hello World</h1><p>This is a test document.</p>';
const converted = htmlDocx.asBlob(html);
const link = document.createElement('a');
link.href = URL.createObjectURL(converted);
link.download = 'document.docx';
link.click();
URL.revokeObjectURL(link.href);
},
},
};
使用 FileSaver 保存文件
安装 FileSaver 库:

npm install file-saver
结合 docx 或 html-docx-js 使用:
import { saveAs } from 'file-saver';
// 结合 docx 使用
Packer.toBlob(doc).then((blob) => {
saveAs(blob, 'example.docx');
});
使用第三方 API 生成 Word 文档
如果需要更复杂的文档生成,可以考虑使用第三方 API,如 DocRaptor 或 Aspose.Words。这些服务通常提供更丰富的功能,但可能需要付费。
注意事项
- 确保在生成文档后释放 Blob URL,避免内存泄漏。
- 对于复杂的文档格式,可能需要更深入地学习 docx 或其他库的 API。
- 测试生成的文档在不同版本的 Microsoft Word 或其他办公软件中的兼容性。






