赞
踩
项目需求要有导出echrts的功能,原本以为只是用echrts自带的那个toolbox里面的导出就行了,结果看了下效果,不尽人意,那个导出只是截图当前视图的png格式,要是数据没标点在统计图上的话,只能看个模糊的大概,有滚动条的话也截不全数据。所以只能各种资源搜索去解决,不过网上好像没有特别全的攻略,都是导出excel,或者pdf格式的居多。特此整理个版本,希望能帮助到搜索到有相同需求的朋友。
export const htmlTemplate = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.2.1/echarts.common.js"></script> <script src="%echartUrl%"></script> <title>指标导出图表</title> </head> <style> * { margin: 0; height: 0; } .showTitle{ font-weight: bold; font-size: 22px; text-align:center; line-height:80px; display:none; display:%letShow%; } .showSubTitle{ font-weight: bold; font-size: 18px; text-align:center; line-height:140px; display:none; display:%letShow1%; } </style> <body> <div class="showTitle">%tmpTitle%</div> <div class="showSubTitle">%tmpSubTitle%</div> <div id="tmpCharts" style="width: 100%;height: 90vh;margin-top:5vh"></div> </body> <script> var colors = ["#5470C6", "#91CC75", "#EE6666"]; var myChart = echarts.init(document.getElementById("tmpCharts")); window.addEventListener("resize",myChart.resize) myChart.setOption(%tmp%); </script> </html>`;
这个是字符串模板的代码,可以放在utils下,如图
项目中引用此模板,并用变量去替换字符串模板,从而是代码导入到html模板中
exportEcharts() { let exportName = this.$refs.rptKindList.selected .map((v) => v.label) .join(); // this.nameList = exportName; // 读取模版文件 let charsOptionStr = JSON.stringify(this.chartsOptions); let echartsUrl = `${location.origin}/js/echarts.js`; let tmpTitle = "统计维度:" + exportName; let tmpSubTitle = "TOP:" + this.formInline.top; console.log(htmlTemplate); let htmlFiles = htmlTemplate .replace(`%tmp%`, charsOptionStr) .replace(`%echartUrl%`, echartsUrl) .replace(`%tmpTitle%`, tmpTitle) .replace(`%tmpSubTitle%`, tmpSubTitle) .replace(`%letShow%`, "block") .replace(`%letShow1%`, "block"); // 导出 var chart = document.createElement("a"); var url = window.URL.createObjectURL( new Blob([htmlFiles], { type: "", }) ); chart.href = url; chart.download = "指标使用情况统计图(" + exportName + ")TOP-" + this.formInline.top + ".html"; chart.click(); window.URL.revokeObjectURL(url); },
因为我们项目运行环境是在内网下的,所以资源只能整到项目下。可以在上面字符串模板的js里面引入个CDN,如下图,这样导出来的html文件在外网也能查看
以上就是整体导出的思路及部分代码,希望能对你有所帮助!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。