vue 项目导出word格式文件

插件安装:

//运行环境安装以下模块:docxtemplater、pizzip、jszip-utils、file-saver、docxtemplater-image-module-free
//各个模块初始化,可以单独存储为js文件,然后调用
import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
import ImageModule from 'docxtemplater-image-module-free'; //图片有关的
import fly from './request.js';

/**
 4. 导出docx
 5. @param { String } tempDocxPath 模板文件路径
 6. @param { Object } data 文件中传入的数据
 7. @param { String } fileName 导出文件名称
*/
export const exportDocx = (tempDocxPath, data, fileName) => {
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      throw error;
    }
    
    
    
    //图片模块
    var opts = {}
    opts.centered = false;
      opts.getImage = function (tagValue, tagName) {
          tagValue  = fly.config.IMG_URL + tagValue
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      }
      opts.getSize = function (img, tagValue, tagName) {
          tagValue  = fly.config.IMG_URL + tagValue
        // FOR FIXED SIZE IMAGE :
         return [470, 210];//图片大小 (这个可以写成动态的,开发文档上有)
        return new Promise(function (resolve, reject) {
          var image = new Image();
          image.src = url;
          image.onload = function () {
            resolve([image.width, image.height]);
          };
          image.onerror = function (e) {
            console.log('img, tagValue, tagName : ', img, tagValue, tagName);
            reject(e);
          }
        });
      }
      var imagemodule = new ImageModule(opts);
      //zip模块
      let zip = new PizZip(content);
    
    let doc = new docxtemplater().loadZip(zip).attachModule(imagemodule).compile();
    
    
        doc.resolveData(data).then(function () {
            try {
                // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
                doc.render();
                var out = doc.getZip().generate({
                  type: "blob",
                  mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                });
                //输出文档
                saveAs(out, fileName);
                
              } catch (error) {
                let e = {
                  message: error.message,
                  name: error.name,
                  stack: error.stack,
                  properties: error.properties,
                };
                console.log({
                  error: e
                });
                // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
                throw error;
              }
            
        });
        
    })
    
    
    
    
};

引入:

import { exportDocx } from '../../assets/js/docx.js';

调用:

//downloadUrl:模板文件路径  data:要导出的数据   filename:导出的文件名
exportDocx(downloadUrl,data,filename);

模板文件语法:

截屏2020-12-09 18.53.45.png

参考链接:https://www.jianshu.com/p/b3622d6f8d98
https://docxtemplater.readthedocs.io/en/latest/index.html

推荐阅读更多精彩内容