vue怎么实现导出word
使用 docx 库生成 Word 文件
安装 docx 库:
npm install docx
在 Vue 组件中引入并创建 Word 文档:
import { Document, Paragraph, Packer, TextRun } from 'docx';
export default {
methods: {
exportToWord() {
const doc = new Document({
sections: [{
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
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
将 HTML 内容转换为 Word:
import htmlDocx from 'html-docx-js';
export default {
methods: {
exportHtmlToWord() {
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 保存文件
安装 file-saver:

npm install file-saver
结合 docx 使用 FileSaver:
import { saveAs } from 'file-saver';
import { Document, Packer } from 'docx';
export default {
methods: {
exportWithFileSaver() {
const doc = new Document({
sections: [{
children: [
new Paragraph({
text: "Example document",
}),
],
}],
});
Packer.toBlob(doc).then(blob => {
saveAs(blob, 'example.docx');
});
},
},
};
使用模板引擎动态生成内容
结合模板引擎如 Mustache 或 Handlebars 动态生成 Word 内容:
import { Document } from 'docx';
import Mustache from 'mustache';
export default {
data() {
return {
templateData: {
title: "Report",
items: ["Item 1", "Item 2", "Item 3"]
}
};
},
methods: {
exportTemplatedWord() {
const template = `
{{title}}
{{#items}}
- {{.}}
{{/items}}
`;
const rendered = Mustache.render(template, this.templateData);
const doc = new Document({
sections: [{
children: [
new Paragraph({
text: rendered,
}),
],
}],
});
// 使用 Packer 导出...
},
},
};
服务器端生成 Word 文件
通过 API 调用服务器端生成 Word:
export default {
methods: {
exportFromServer() {
axios.post('/api/generate-word', { data: this.formData }, {
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();
});
},
},
};
注意事项
- 样式处理:Word 文档的样式需要通过库的 API 设置,无法直接使用 CSS
- 复杂格式:对于表格、图片等复杂内容,需要查阅具体库的文档
- 浏览器兼容性:Blob URL 方式在主流浏览器中都支持
- 文件大小:大文档建议使用服务器端生成






