vue怎么实现导出word
Vue 实现导出 Word 的方法
在 Vue 项目中,可以通过以下几种方法实现导出 Word 文档的功能:
使用 docx 库生成 Word 文档
安装 docx 库:
npm install docx
创建一个简单的 Word 文档并导出:

import { Document, Paragraph, Packer, TextRun } from 'docx';
export default {
methods: {
exportToWord() {
const doc = new Document({
sections: [{
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 = 'document.docx';
link.click();
URL.revokeObjectURL(link.href);
});
},
},
};
使用 html-docx-js 将 HTML 转换为 Word
安装 html-docx-js:
npm install html-docx-js
将 HTML 内容转换为 Word 文档:

import htmlDocx from 'html-docx-js';
export default {
methods: {
exportToWord() {
const htmlContent = '<h1>Hello World</h1><p>This is a test document.</p>';
const converted = htmlDocx.asBlob(htmlContent);
const link = document.createElement('a');
link.href = URL.createObjectURL(converted);
link.download = 'document.docx';
link.click();
URL.revokeObjectURL(link.href);
},
},
};
使用 FileSaver 保存文件
安装 file-saver:
npm install file-saver
结合 docx 或 html-docx-js 使用 FileSaver 保存文件:
import { saveAs } from 'file-saver';
import htmlDocx from 'html-docx-js';
export default {
methods: {
exportToWord() {
const htmlContent = '<h1>Hello World</h1>';
const converted = htmlDocx.asBlob(htmlContent);
saveAs(converted, 'document.docx');
},
},
};
使用后端服务生成 Word 文档
如果需要更复杂的 Word 文档(如模板填充),可以通过后端服务生成 Word 文件,前端调用接口下载:
export default {
methods: {
exportToWord() {
axios.get('/api/export-word', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'document.docx');
document.body.appendChild(link);
link.click();
link.remove();
});
},
},
};
注意事项
- 使用
docx库可以生成复杂的 Word 文档,但需要熟悉其 API。 html-docx-js适合将简单的 HTML 转换为 Word,但可能不支持所有 CSS 样式。- 后端生成适合处理复杂模板或大量数据的情况。
根据需求选择合适的方法,以上方法均可在 Vue 2 或 Vue 3 中使用。






