Exporting Tables and ECharts Charts in Vue 3 to Word Documents

Install Required Packages

// Install docxtemplater
npm install docxtemplater pizzip --save
// Install jszip-utils
npm install jszip-utils --save 
// Install jszip
npm install jszip --save
// Install FileSaver
npm install file-saver --save
// Install docxtemplater-image-module-free
npm install --save docxtemplater-image-module-free 

Import Packages

Create a new file named xxx.ts and import the packages:

import docxtemplater from 'docxtemplater';
import ImageModule from "docxtemplater-image-module-free";
import { saveAs } from 'file-saver';
import JSZipUtils from 'jszip-utils';
import PizZip from 'pizzip';

ECharts Format Conversion Method

Add the following functon to xxx.ts:

/**
 * Convert ECharts Chart Format
 * 
 **/
// Export ECharts image, format conversion, provided by official, no need to modify
function base64DataURLToArrayBuffer(dataURL) {
  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;
}

Export Word Method

Add the following method to xxx.ts:

/**
 * Export Word Document
 * @param {Object} tempDocxPath Template File Path
 * @param {Object} wordData Export Data
 * @param {Object} fileName Export File Name
 **/
export function exportWord(tempDocxPath: any, wordData: any, fileName: any, myChart2: any) {
 // Parameters are template path, table data, file name, and ECharts instance on the page
  // Load the image processing plugin, which is included with docxtemplater
  const str: { image: any; }[] = [];

  // Read and get the binary content of the template file
  JSZipUtils.getBinaryContent(tempDocxPath, function (error: any, content: any) {
    if (error) {
      throw error;
    }

    // Create a PizZip instance with the template content
    let zip = new PizZip(content);
    // Create and load the docxtemplater instance object
    let doc = new docxtemplater();
    doc.loadZip(zip);

    str.push({
      image: myChart2.getDataURL({
        pixelRatio: 2,      // Exported image resolution ratio, default is 1.
        backgroundColor: '#fff'
      })
    })
    // Image processing
    const opts = {
    };
    opts.centered = true; // Image centered, defined in the Word template as {%%image}
    opts.fileType = "docx";
    opts.getImage = (chartId: any) => {
      return base64DataURLToArrayBuffer(chartId);
    };
    opts.getSize = () => {
      return [600, 300];
    };
    const imageModule = new ImageModule(opts);

    doc.attachModule(imageModule);

    doc.setData({ ...wordData, chartList: str });

    try {
      // Replace all template variables with values
      doc.render();
    } catch (error) {
      // Throw exception
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      };
      console.log(JSON.stringify({
        error: e
      }));
      throw error;
    }

    // Generate a zip file representing the docxtemplater object (not a real file, but an in-memory representation)
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    });
    // Save the target file as the specified type and name
    saveAs(out, fileName + ".docx");
  });
};

Word Template (Template Must Be in Public Folder)

Use

Importt xxx.ts in the page where it is used:

exportWord(
	'./../../../../public/template.docx', // Template Path
	{ list: tableData.value }, // Data
	'统计数据',// Export File Name
	myChart.value// Declared ECharts Name
);

Tags: vue export Word echarts Table

Posted on Sat, 03 Oct 2026 16:54:23 +0000 by seran128