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("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
],
}],
});
Packer.toBlob(doc).then(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'document.docx';
link.click();
URL.revokeObjectURL(url);
});
}
}
}
使用 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 url = URL.createObjectURL(converted);
const link = document.createElement('a');
link.href = url;
link.download = 'document.docx';
link.click();
URL.revokeObjectURL(url);
}
}
}
使用 FileSaver.js 保存文件
安装 FileSaver:

npm install file-saver
结合 docx 使用 FileSaver:
import { saveAs } from 'file-saver';
import { Document, Packer, Paragraph, TextRun } from 'docx';
export default {
methods: {
exportWithFileSaver() {
const doc = new Document({
sections: [{
children: [
new Paragraph("Hello World")
]
}]
});
Packer.toBlob(doc).then(blob => {
saveAs(blob, 'document.docx');
});
}
}
}
使用模板方法
创建 Word 模板文件 (.dotx) 并使用 docxtemplater:
npm install docxtemplater pizzip
实现代码:
import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import { saveAs } from 'file-saver';
export default {
methods: {
exportWithTemplate() {
// 加载模板文件
fetch('/template.docx')
.then(response => response.arrayBuffer())
.then(buffer => {
const zip = new PizZip(buffer);
const doc = new Docxtemplater().loadZip(zip);
doc.setData({
name: 'John',
age: 30
});
try {
doc.render();
} catch (error) {
console.error(error);
}
const out = doc.getZip().generate({ type: 'blob' });
saveAs(out, 'output.docx');
});
}
}
}
注意事项
确保在浏览器环境中使用这些方法,部分库可能不支持 SSR 对于复杂文档,考虑使用专业文档生成库如 docx 或模板引擎 处理大文件时要注意性能问题,可能需要分块处理 跨浏览器测试导出功能,不同浏览器可能有不同的行为限制






