Export the graph of echarts to the excel table in vue

Export the graph of echarts to the excel table through the plug-in exceljs and file-saver in vue

1. The effect achieved

insert image description here

2. Install libraries such as echarts, exceljs and file-saver

npm install exceljs file-saver --save
npm install echarts --save

3. Specific implementation code

After installing the corresponding library, the height and width attributes must be given when rendering the echarts graph, otherwise the graph may not be displayed.

<template>
  <div>
    <div ref="chart" id="lineChart" style="height: 400px; width: 800px"></div>
    <el-button @click="exportExcel"> 导出图表</el-button>
  </div>
</template>

<script>
import * as echarts from 'echarts'; // 引入echarts, * as echarts 表示引入所有的方法
import ExcelJS from 'exceljs';    // 引入exceljs, 用于生成excel文件
import {
    
     saveAs } from 'file-saver' // 引入file-saver, 用于保存文件


export default {
    
    
  data() {
    
    
    return {
    
    
      chart: null,
    }
  },
  mounted() {
    
    
    this.chart = echarts.init(this.$refs.chart);

    // 绘制图表
    const option = {
    
    
      title: {
    
    
        text: 'Echarts 示例'
      },
      tooltip: {
    
    },
      legend: {
    
    
        data: ['数据']
      },
      xAxis: {
    
    
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
    
    },
      series: [{
    
    
        name: '数据',
        type: 'bar',
        data: [100, 200, 300, 400, 500, 600],
        markLine: {
    
    
          data: [
            {
    
     type: 'average', name: '平均值' }
          ]
        }
      }]
    };
    this.chart.setOption(option);
  },
  methods: {
    
    
    exportExcel() {
    
    
      const workbook = new ExcelJS.Workbook(); // 创建工作簿
      const worksheet = workbook.addWorksheet('Sheet1'); // 添加工作表

      const chart = echarts.getInstanceByDom(this.$refs.chart) // 获取图表实例
      const base64Image = chart.getDataURL({
    
    
        pixelRatio: 2, // 导出图片的分辨率比例,默认为1,即图片的分辨率为屏幕分辨率的一倍
        backgroundColor: '#fff' // 导出图片的背景色
      })
      let image= workbook.addImage({
    
     // 添加图片
          base64: base64Image, // 图片的base64编码
          extension: 'png'  // 图片的扩展名
        });
        worksheet.addImage(image, 'A1:J20'); // 将图片添加到工作表中
        workbook.xlsx.writeBuffer().then(function (buffer) {
    
     // 生成excel文件的二进制数据
        saveAs.saveAs(new Blob([buffer], {
    
      // 生成Blob对象
          type: 'application/octet-stream'  // 指定文件的MIME类型
        }), 'xchart.xlsx');  // 指定文件名
      });
    }
  }
}
</script>


Guess you like

Origin blog.csdn.net/qq_36660135/article/details/130015354