vue导出word文档遇到的问题


一、安装依赖

docxtemplater pizzip jszip-utils file-saver

先安装这四个依赖

二、创建docx.js文件

1.引入库

import docxtemplater from docxtemplater;
import PizZip from pizzip;
import JSZipUtils from jszip-utils;
import {
          
    saveAs } from file-saver;

export const exportDocx = (path, data, fileName) => {
          
   
    JSZipUtils.getBinaryContent(path, (error, content) => {
          
   
      if (error) {
          
   
        throw error;
      }
      let zip = new PizZip(content);
      let doc = new docxtemplater().loadZip(zip);
      doc.setData(data);
      try {
          
   
        doc.render();
      } catch (error) {
          
   
        let e = {
          
   
          message: error.message,
          name: error.name,
          stack: error.stack,
          properties: error.properties,
        };
        console.log({
          
   
          error: e
        });
        throw error;
      }
      let out = doc.getZip().generate({
          
   
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      }); //Output the document using Data-URI
      saveAs(out, fileName);
    });
  };

2.页面中引入docx.js文件

import {
          
    exportDocx } from @/utils/docx;
download(){
          
   
	let datas = {
          
   
		title: "xxx",
		table: data //数据请求
	}
	exportDocx( uri,datas, `xxx文件.docx`);
}

3.解决问题

uri的路径: 关于exportDocx传入的word模板的路径问题,如果是vue-cli是版本2 word模板要放在static的文件夹下,如果是vue-cli是版本3,word模板要放在public文件夹下。路径错误的话报错Can‘t find end of central directory : is this a zip file ? word模板赋值: 上面datas的table的数据在模板内展示,word模板开头要以{#table}开头,{/table}结束,不然会报错Uncaught Error: TemplateError: Multi error at XMLHttpRequest.xhr.onreadystatechange

经验分享 程序员 微信小程序 职场和发展