一、下载所需要的包
//-- 安装 docxtemplater
npm install docxtemplater pizzip --save
//-- 安装 jszip-utils
npm install jszip-utils --save
//-- 安装 jszip
npm install jszip --save
//-- 安装 FileSaver
npm install file-saver --save
//--安装 docxtemplater-image-module-free
npm install --save docxtemplater-image-module-free
二、 引入包
新建一个xxx.ts文件,引入包
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 格式转换方法
xxx.ts文件中,写入 echarts 官网自带的转化 base64 格式的方法
/**
* echarts 图表格式转换
*
* **/
// 导出echarts图片,格式转换,官方自带,不需要修改
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;
}
四、导出worder 方法
在xxx.ts文件中写入 导出的方法
/**
* 导出 Word 文档
* @param {Object} tempDocxPath 模板文件路径
* @param {Object} wordData 导出数据
* @param {Object} fileName 导出文件名
**/
export function exportWord(tempDocxPath: any, wordData: any, fileName: any, myChart2: any) {
// 参数分别为 模板路径、表格数据、导出文件名称、页面中echarts实例
//这里要引入处理图片的插件,下载docxtemplater后,引入的就在其中了
const str: { image: any; }[] = [];
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(tempDocxPath, function (error: any, content: any) {
if (error) {
throw error;
}
// 创建一个PizZip实例,内容为模板的内容
let zip = new PizZip(content);
// 创建并加载docxtemplater实例对象
let doc = new docxtemplater();
doc.loadZip(zip);
str.push({
image: myChart2.getDataURL({
pixelRatio: 2, // 导出的图片分辨率比例,默认为 1。
backgroundColor: '#fff'
})
})
// 图片处理
const opts = {
};
opts.centered = true; // 图片居中,在word模板中定义方式为{%%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 {
// 用模板变量的值替换所有模板变量
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;
}
// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
let out = doc.getZip().generate({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
// 将目标文件对象保存为目标类型的文件,并命名
saveAs(out, fileName + ".docx");
});
};
五、worder模板(模板必须放在public文件下)
六、使用
在使用的页面中引入 xxx.ts 文件
exportWord(
'./../../../../public/template.docx', // 模板路径
{ list: tableData.value }, // 数据
'统计数据',// 导出文件名称
myChart.value// 声明的 echarts名称
);
七、效果图