实现这个功能我们用到一个插件 docxtemplater
一.引入包
import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
二.建立本地的模板(变量渲染到里面)
可以把模板放到项目里
![vue导出echarts图表及文本到word_第1张图片](http://img.e-com-net.com/image/info8/3c0c30294456416484046491c3500e7e.jpg)
三.代码
data() {
return {
form: {
custName: "杰克",
phoneNumber: "1234567890",
projectRequirement: "为了更美好的明天而战",
totalPrice: 666,
},
tableData: [],
img1: '',
img2: ''
};
},
此处渲染规则
单个变量模板中直接用{}
表格变量对应{#table} {/table}
图片{%} 图片渲染,先把echarts转换为base64格式,再到模板上解码
图片居中{%%}
this.img2 = myChart2.getDataURL({
pixelRatio: 2,
backgroundColor: '#fff'
});
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;
},
exportWord: function() {
var ImageModule = require('docxtemplater-image-module-free');
var fs = require("fs");
const expressions = require("angular-expressions");
let _this = this;
JSZipUtils.getBinaryContent("input.docx", function(error, content) {
if (error) {
throw error;
};
expressions.filters.size = function (input, width, height) {
return {
data: input,
size: [width, height],
};
};
function angularParser(tag) {
const expr = expressions.compile(tag.replace(/’/g, "'"));
return {
get(scope) {
return expr(scope);
},
};
}
let opts = {}
opts = { centered: false };
opts.getImage = (chartId)=> {
return _this.base64DataURLToArrayBuffer(chartId);
}
opts.getSize = function(img, tagValue, tagName) {
if (tagName === "img2") return [400,250];
return [600,350];
}
let zip = new PizZip(content);
let doc = new docxtemplater();
doc.attachModule(new ImageModule(opts));
doc.loadZip(zip);
console.log(_this.logo);
doc.setData({
..._this.form,
table: _this.tableData,
img1: _this.img1,
img2: _this.img2
});
try {
doc.render();
} catch (error) {
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
};
console.log(JSON.stringify({ error: e }));
throw error;
}
let out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
saveAs(out, "demo.docx");
});
}
导出显示
![vue导出echarts图表及文本到word_第2张图片](http://img.e-com-net.com/image/info8/795d6a4d692b4ddc8cd0ebef600bd9e9.jpg)
![vue导出echarts图表及文本到word_第3张图片](http://img.e-com-net.com/image/info8/e0623bd0eeff41be9c478f8ce1ea7ca0.jpg)