vue实现word下载功能
使用 docx 库生成并下载 Word 文件
安装 docx 库和 file-saver 库:
npm install docx file-saver --save
在 Vue 组件中引入所需库:
import { Document, Paragraph, Packer, TextRun } from 'docx';
import { saveAs } from 'file-saver';
创建 Word 文档内容并触发下载:
export default {
methods: {
generateWordDocument() {
const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
],
}]
});
Packer.toBlob(doc).then(blob => {
saveAs(blob, "example.docx");
});
}
}
}
使用 html-docx-js 转换 HTML 为 Word
安装 html-docx-js 和 file-saver:
npm install html-docx-js file-saver --save
在组件中使用:
import htmlDocx from 'html-docx-js';
import { saveAs } from 'file-saver';
export default {
methods: {
exportAsWord() {
const html = '<h1>Hello World</h1><p>This is a test document</p>';
const converted = htmlDocx.asBlob(html);
saveAs(converted, 'document.docx');
}
}
}
使用后端 API 下载 Word 文件
前端发起请求:
export default {
methods: {
downloadWordFile() {
axios.get('/api/download-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', 'file.docx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
}
}
使用模板填充数据生成 Word
安装 docxtemplater:
npm install docxtemplater pizzip file-saver --save
实现代码:
import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import { saveAs } from 'file-saver';
export default {
methods: {
generateFromTemplate() {
// 加载模板文件
axios.get('/template.docx', { responseType: 'arraybuffer' })
.then(response => {
const zip = new PizZip(response.data);
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');
});
}
}
}
注意事项
确保在浏览器环境中使用这些方法时处理可能的兼容性问题。
对于复杂文档生成需求,考虑使用后端服务处理文档生成,前端仅负责下载。
大文件生成时需要考虑性能优化和内存管理。







