vue 导出word文档 (纯有效) 报错: Can‘t find end of central directory : is this a zip file ?

博客围绕Vue项目中Word文件导出报错展开,报错信息为‘Can't find end of central directory : is this a zip file?’,给出将path路径替换的解决方案,还提及安装依赖、项目导入、word模板、文件路径、导出按钮函数代码等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错:  Can't find end of central directory : is this a zip file ?

解决方案:把path路径换成:

  `${"/yuqindemo"}.docx`

安装依赖:

npm install file-saver@2.0.5 --save
npm install docxtemplater@3.26.3 --save
npm install jszip@3.7.1 --save
npm install jszip-utils@0.1.0 --save
npm install pizzip@3.1.1 --save

vue项目中导入:

import JSZipUtils from "jszip-utils";
import JSZip from "pizzip";
import Docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";

word模板:

文件路径:

 导出按钮函数代码

 exportWord() {
      const that = this;
      // 读取并获得模板文件的二进制内容"
      JSZipUtils.getBinaryContent(`${"/yuqindemo"}.docx`, (error, content)=> {
         console.log(error,content)
        // 抛出异常
        if (error) {throw error;}
        // 创建一个PizZip实例,内容为模板的内容
        const zip = new JSZip(content);
        // 创建并加载docxtemplater实例对象
        const doc = new Docxtemplater().loadZip(zip);
        // 设置模板变量的值
        doc.setData({
          isTable: [{index:1,title:"小张",url:'http://localhost:8080', name:"测试数据",img:'小张'}], // 文档中循环数据
        });
        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          const e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          };
          console.log(JSON.stringify({ error: e }));
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
        const out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        // 将目标文件对象保存为目标类型的文件,并命名
        saveAs(out, [{index:1,title:"小张",url:'http://localhost:8080',name:"测试数据",img:'小张'}] + "做题记录表.docx");
      });
    },

导出后

结束 over over!

前端开发综合网站: 编程设计网站

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值