JS exports Echarts icon data to Excel table

The development requirements require adding a button in the upper right corner of the Echarts chart to download the chart data to Excel. After obtaining all the echarts data below, the requirements are completed by manually arranging and wrapping the data through js.

HTML structure:

 <template>
    <div style="cursor: pointer; position: absolute; right: 1rem; z-index: 10">
      <el-tooltip
        v-if="Option?.legend"
        popper-class="download_tooltip"
        placement="bottom"
        content="保存为Excel"
        effect="light"
        :show-arrow="false"
        hide-after="0"
      >
        <el-button
          class="light_button"
          type="text"
          plain
          icon="Document"
          @click="downloadExcel()"
        ></el-button>
      </el-tooltip>
    </div>
</template>

JS code:

const downloadExcel = () => {
 let str = "";
  str = [...Option.legend.data].unshift("日期");
  str = str.join(",") + "\n";//图例数据作为标题,逗号隔开代表一个单元格
  const legend = props.Option.legend.data; //获取到图例数据
  const series = props.Option.series;  //获取到图表数据
  const xAxis = props.Option.xAxis.data; //x轴数据作为excel表格第一列数据
  const seriesData = {};
  series.forEach((item) => {
    seriesData[item.name] = item.data; //将图表每列标题与数据对应
  });
  xAxis.forEach((item, i) => {
    str += `${item + "\t"},`; //往str添加每行第一个数据
    legend.forEach((el) => {
      str += `${seriesData[el][i] + "\t"},`; //添加进去图表每行对应的数据
    });
    str += "\n";//添加完一行后就换行
  });
  //防止中文乱码
  const uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
  const link = document.createElement("a"); //在页面创建a链接并点击下载文件
  link.href = uri;
  // 对下载的文件命名
  link.download = `${Option.title.text}.csv`;
  link.click();
}

Guess you like

Origin blog.csdn.net/SunFlower914/article/details/128835771