echarts exports data to Excel files (overriding the dataview method)
Preface
This article implements exporting data to Excel files in the echarts graphics plug-in under Vue by saving the front-end.
code
This article implements a vue front-end project. The following codes are all codes under vue.
Remember to import the following two packages at the beginning. If they are not installed, enter npm install file-saver and npm install xlsx in the terminal to install them.
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
//后面就是你的代码
The next step is to rewrite the dataView part under the feature in the toolbox.
For relevant knowledge, you can also read the official documentation. Click [ here ] for the official documentation.
toolbox: {
feature: {
dataView: {
show: true,
lang: ['数据视图', '关闭', '导出Excel'],
//optionToContent为重画表格的函数
optionToContent: function(opt){
//axisData是你想定义的表格第一列的数据,我这里设置为柱形图的x轴数据
var axisData = opt.xAxis[0].data;
//tAxis[0]为你想定义的表格第一行的数据
var txisData = opt.tAxis[0].data;
var series = opt.series;
//表头
var tdHeads = '<td style="padding: 0 10px"></td>';
var tdBodys = '';
var nameData = txisData;
for (var i = 0; i < nameData.length ; i++) {
tdHeads += '<td style="padding: 0 10px">' + nameData[i] + '</ td >';
}
var table = '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
for (var i = 0, l = axisData.length; i < l; i++) {
for (var j = 0; j < series.length; j++) {
var temp = series[j].data[i];
if (temp != null && temp != undefined) {
tdBodys += '<td>' + temp + '</td>';
} else {
tdBodys += '<td></td>';
}
}
table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';
tdBodys = '';
}
table += '</tbody></table>';
return table;
},
//contentToOption为重写“刷新”按钮的语句
contentToOption: function (HTMLDomElement, opt) {
let et = XLSX.utils.table_to_book(
document.getElementById("Mytable")
);
let etout = XLSX.write(et, {
bookType: "xlsx",
bookSST: true,
type: "array",
});
try {
FileSaver.saveAs(
new Blob([etout], {
type: "application/octet-stream",
}),
"头部文件名" + "-" + new Date().toLocaleString() +".xlsx"
);
} catch (e) {
}
return etout;
},
},
magicType: {show: true},
restore: {show: true},
saveAsImage: {show: true},
// dataZoom: {show: true},
}
Realize the effect
Click the data view in the upper right corner of the icon
Click on the lower right corner to export Excel and download it directly.
Download to a local Excel file.