首页 > 技术文章 > 导出word

zhenggaowei 2020-08-07 10:33 原文

import { Message } from 'element-ui';
const docxtemplater = require('docxtemplater')
const PizZip = require('pizzip');
const JSZipUtils = require('jszip-utils');
const saveAs = require('file-saver').saveAs;
const base64DataURLToArrayBuffer = (dataURL:any) => {
  const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  }
  const stringBase64 = dataURL.replace(base64Regex, '');
  let binaryString;
  if (typeof window !== 'undefined') {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = new Buffer(stringBase64, 'base64').toString('binary');
  }
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes.buffer;
};
/**
 * 导出word
 * @param {*} templateUrl 模板文件路径
 * @param {*} fileName 导出文件名称
 * @param {*} data 模板数据
 */
const exportWord = (templateUrl: string, fileName: string, data: any, userOption: any = {}) => {
  const ImageModule = require('open-docxtemplater-image-module');
  JSZipUtils.getBinaryContent(templateUrl, (error: any, content: any) => {
    if (error) {
      Message.warning('没有找到文件模板,无法导出!');
      throw error;
    }
    const zip = new PizZip(content);
    let opts:any = {};
    opts.centered = true; // 图片居中,在word模板中定义方式为{%%image}
    opts.fileType = 'docx';
    opts.getImage = (dataURL:any) => {
      return base64DataURLToArrayBuffer(dataURL);
    };
    opts.getSize = (img: any, tagValue: any, tagName: string) => {
      return [600, 400];
    };
    opts = Object.assign(opts, userOption);
    const imageModule = new ImageModule(opts);
    const doc = new docxtemplater().attachModule(imageModule).loadZip(zip);
    doc.setData(data);
    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'
    });
    console.log(out);
    // 将目标文件对象保存为目标类型的文件,并命名
    saveAs(out, `${fileName}.doc`);
  });
};

export default exportWord;

 

推荐阅读