1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| <template> <div> <button @click="exportWord">导出 Word</button> </div> </template>
<script> import docxtemplater from "docxtemplater"; import PizZip from "pizzip"; import JSZipUtils from "jszip-utils"; import { saveAs } from "file-saver";
export default { data() { return { // 模拟数据,用于填充 Word 模板 exportData: { name: "张三", items: [ { name: "项目1", description: "描述1", colspan: 2, rowspan: 1 }, { name: "项目2", description: "描述2", colspan: 1, rowspan: 2 }, ], }, }; }, methods: { exportWord() { // 指定模板文件路径(放在 public 文件夹中) //注意(vue2/public,vue3/static),如果有qiankun主子应用,请把word模板放在主应用public下 const templatePath = "/template.docx"; // 指定导出的文件名 const fileName = "output.docx";
// 使用 JSZipUtils 加载模板文件 JSZipUtils.getBinaryContent(templatePath, (error, content) => { if (error) { throw error; }
// 创建 PizZip 实例 const zip = new PizZip(content); // 创建 docxtemplater 实例 const doc = new docxtemplater().loadZip(zip);
// 设置数据到模板 doc.setData(this.exportData);
try { // 渲染模板 doc.render(); } catch (error) { const e = { message: error.message, name: error.name, stack: error.stack, properties: error.properties, }; console.error(JSON.stringify({ error: e })); throw error; }
// 生成 Word 文件 const out = doc.getZip().generate({ type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", });
// 保存文件 saveAs(out, fileName); }); }, }, }; </script>
<style scoped> button { padding: 10px 20px; font-size: 16px; cursor: pointer; } </style>
|