vue +echarts+ docxtemplater导出word和多张图表图片

2023-10-14 07:59

本文主要是介绍vue +echarts+ docxtemplater导出word和多张图表图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

vue +echarts+ docxtemplater导出word和多张图表图片

  • 前期准备

前期准备

1、按照依赖的插件docxtemplater、pizzip、jszip-utils、jszip、FileSaver、docxtemplater-image-module-free。

//-- 安装 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 

2、引入依赖

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 '

注:若引入docxtemplater-image-module-free 报错时,可尝试使用require方法引入。

let ImageModule = require('docxtemplater-image-module-free');

3、代码-父组件
我是把table通过插槽的方式注入到子组件的

<template><div class="box">
<wordexportFileName="测试666"templateFileName="templateFile":wordData="wordData":chartOptions="chartOptions"><template v-slot:table><table cellspacing="0"><caption>标题</caption><tr><td class="key-name">标题1</td><td colspan="3">{{ wordData.a }}</td></tr><tr><td class="key-name">标题2</td><td colspan="3">{{ wordData.b }}</td></tr><tr><td class="key-name">标题3</td><td colspan="3">{{ wordData.c }}</td></tr><tr><td class="key-name">标题4</td><td>{{ wordData.d }}</td><td class="key-name">标题6</td><td>{{ wordData.f }}</td></tr><tr><td class="key-name">标题5</td><td>{{ wordData.e }}</td><td class="key-name">标题7</td><td>{{ wordData.g }}</td></tr><tr><td colspan="4" class="key-name options">审批意见</td></tr><tr><td colspan="4" class="options">{{ wordData.h }}</td></tr><tr v-for="(item, index) in wordData.list" :key="index"><td class="key-name">姓名</td><td>{{ item.name }}</td><td class="key-name">电话</td><td>{{ item.phone }}</td></tr></table></template></word>
</div>
</template>
<script>
// 子组件
import word from "@/components/exportWord.vue";
export default {components: { word },data() {return {// 导出wordwordData: {a: "这是标题1内容",b: "这是标题2内容",c: "这是标题3内容",d: "这是标题4内容",e: "这是标题5内容",f: "这是标题6内容",g: "这是标题7内容",h: "同意",list: [{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },],},// 图表chartOptions: [// echarts图表的option// 第一个图表{title: {text: "某站点用户访问来源",subtext: "纯属虚构",left: "center",},tooltip: {trigger: "item",},legend: {orient: "vertical",left: "left",},series: [{name: "访问来源",type: "pie",radius: "50%",data: [{ value: 1048, name: "搜索引擎" },{ value: 735, name: "直接访问" },{ value: 580, name: "邮件营销" },{ value: 484, name: "联盟广告" },{ value: 300, name: "视频广告" },],emphasis: {itemStyle: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: "rgba(0, 0, 0, 0.5)",},},},],},// 第二个图表{title: {text: "未来一周气温变化",subtext: "纯属虚构",},tooltip: {trigger: "axis",},legend: {data: ["最高气温", "最低气温"],},xAxis: {type: "category",boundaryGap: false,data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],},yAxis: {type: "value",axisLabel: {formatter: "{value} °C",},},series: [{name: "最高气温",type: "line",data: [10, 11, 13, 11, 12, 12, 9],markPoint: {data: [{ type: "max", name: "最大值" },{ type: "min", name: "最小值" },],},markLine: {data: [{ type: "average", name: "平均值" }],},},{name: "最低气温",type: "line",data: [1, -2, 2, 5, 3, 2, 0],markPoint: {data: [{ name: "周最低", value: -2, xAxis: 1, yAxis: -1.5 }],},markLine: {data: [{ type: "average", name: "平均值" },[{symbol: "none",x: "90%",yAxis: "max",},{symbol: "circle",label: {position: "start",formatter: "最大值",},type: "max",name: "最高点",},],],},},],},],};},};
</script>

4、代码-子组件

<template><!-- 导出word模版 --><div class="approvalNo-or-opinionNo-list"><el-button type="primary" size="small" @click="exportWord">点击下载</el-button><div id="pdfDom"><slot name="table"></slot></div><divstyle="width: 600px; height: 300px; margin: 0 auto"v-for="(item, index) in chartOptions":key="index"><Echart :options="item" ref="chart"></Echart></div></div>
</template><script>
import docxtemplater from "docxtemplater";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import JSZip from "jszip";
import PizZip from "pizzip";
import Echart from "@/components/Echarts.vue";
export default {components: { Echart },data() {return {};},props: {// 文档数据wordData: {type: Object,default: {},},// 导出文件名字exportFileName: {type: String,default: "word",},// 模版文件名字(文件需放在public目录下,文件格式为docx)templateFileName: {type: String,default: "templateFile",},// 图表option 数组,可多个图表chartOptions: {type: Array,default: [],},},methods: {// 导出echarts图片,格式转换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() {const ImageModule = require("docxtemplater-image-module-free");const that = this;// 存放echarts 图表 base64图片数组const str = [];// 读取并获得模板文件的二进制内容JSZipUtils.getBinaryContent(`${that.templateFileName}.docx`,(error, content) => {if (error) {// 抛出异常throw error;}const zip = new PizZip(content); // 创建一个JSZip实例,内容为模板的内容const doc = new docxtemplater();doc.loadZip(zip); // 创建并加载docxtemplater实例对象//   如果有echarts图表if (that.chartOptions.length > 0) {for (const iterator of that.$refs["chart"]) {// 这个getChartImg方法是我的echart组件中获取echarts图表图片的base64的dataurliterator.getChartImg((chartImg) => {str.push({ image: chartImg });});}// 图片处理const opts = {};opts.centered = true; // 图片居中,在word模板中定义方式为{%%image}opts.fileType = "docx";opts.getImage = (chartId) => {return that.base64DataURLToArrayBuffer(chartId);};opts.getSize = () => {return [600, 300];};const imageModule = new ImageModule(opts);doc.attachModule(imageModule);}doc.setData({ ...that.wordData, chartlist: str }); // 设置模板变量的值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",});// 将目标文件对象保存为目标类型的文件,并命名saveAs(out, `${that.exportFileName}.docx`);});},},
};
</script><style lang="less">
.approvalNo-or-opinionNo-list {height: 350px;overflow-y: auto;padding-bottom: 20px;border-bottom: 1px solid #ccc;> #pdfDom {table {text-align: center;border-bottom: 1px solid #ccc;width: 93%;margin: 0 auto;font-family: "楷体", "楷体_GB2312";caption {font-size: 16px;text-align: center;line-height: 46px;color: #333;font-weight: bold;}td {width: 25%;height: 32px;color: #666;border-left: 1px solid #ccc;border-top: 1px solid #ccc;padding: 0 6px;}td:last-child {border-right: 1px solid #ccc;}.key-name {color: #333;font-weight: 600;}.options {padding: 10px;text-align: justify;text-indent: 2em;}}}
}
</style>

5、getChartImg方法

// 获取图表base64图getChartImg(callback: any) {const that = this as any;callback(that.myChart.getDataURL());},

5、word模版
在这里插入图片描述
6、页面
在这里插入图片描述

7、成功导出后的word
在这里插入图片描述

这篇关于vue +echarts+ docxtemplater导出word和多张图表图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/209174

相关文章

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

Java实战之利用POI生成Excel图表

《Java实战之利用POI生成Excel图表》ApachePOI是Java生态中处理Office文档的核心工具,这篇文章主要为大家详细介绍了如何在Excel中创建折线图,柱状图,饼图等常见图表,需要的... 目录一、环境配置与依赖管理二、数据源准备与工作表构建三、图表生成核心步骤1. 折线图(Line Ch

如何使用CSS3实现波浪式图片墙

《如何使用CSS3实现波浪式图片墙》:本文主要介绍了如何使用CSS3的transform属性和动画技巧实现波浪式图片墙,通过设置图片的垂直偏移量,并使用动画使其周期性地改变位置,可以创建出动态且具有波浪效果的图片墙,同时,还强调了响应式设计的重要性,以确保图片墙在不同设备上都能良好显示,详细内容请阅读本文,希望能对你有所帮助...

Python脚本实现图片文件批量命名

《Python脚本实现图片文件批量命名》这篇文章主要为大家详细介绍了一个用python第三方库pillow写的批量处理图片命名的脚本,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言源码批量处理图片尺寸脚本源码GUI界面源码打包成.exe可执行文件前言本文介绍一个用python第三方库pi

Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)

《Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)》本文介绍了如何使用Python和Selenium结合ddddocr库实现图片验证码的识别和点击功能,感兴趣的朋友一起看... 目录1.获取图片2.目标识别3.背景坐标识别3.1 ddddocr3.2 打码平台4.坐标点击5.图

Vue3中的动态组件详解

《Vue3中的动态组件详解》本文介绍了Vue3中的动态组件,通过`component:is=动态组件名或组件对象/component`来实现根据条件动态渲染不同的组件,此外,还提到了使用`markRa... 目录vue3动态组件动态组件的基本使用第一种写法第二种写法性能优化解决方法总结Vue3动态组件动态

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

Python利用PIL进行图片压缩

《Python利用PIL进行图片压缩》有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所以本文为大家介绍了Python中图片压缩的方法,需要的可以参考下... 有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所有可以对文件中的图

java获取图片的大小、宽度、高度方式

《java获取图片的大小、宽度、高度方式》文章介绍了如何将File对象转换为MultipartFile对象的过程,并分享了个人经验,希望能为读者提供参考... 目China编程录Java获取图片的大小、宽度、高度File对象(该对象里面是图片)MultipartFile对象(该对象里面是图片)总结java获取图片