我通过WP AdCenter插件通过HighCharts生成图表。我希望用户(管理员和订阅者等)能够以Excel或CSV格式下载驱动图表的原始数据,而不仅仅是图表的PNG,JPG或PDF图像。有没有办法在没有严格修改代码的情况下做到这一点(我不是PHP程序员)。这个额外的导出选项是否可以在不久的将来推出?
答案 0 :(得分:8)
这个jsfiddle可以帮助您从highchart创建excel。 导出菜单中添加的下载CSV 选项正常工作。只要仔细考虑一下,你就会做得更好。
以下是代码:
/**
* A small plugin for getting the CSV of a categorized chart
*/
(function (Highcharts) {
// Options
var itemDelimiter = ',', // use ';' for direct import to Excel
lineDelimiter = '\n';
var each = Highcharts.each;
Highcharts.Chart.prototype.getCSV = function () {
var xAxis = this.xAxis[0],
columns = [],
line,
csv = "",
row,
col;
if (xAxis.categories) {
columns.push(xAxis.categories);
columns[0].unshift("");
}
each (this.series, function (series) {
columns.push(series.yData);
columns[columns.length - 1].unshift(series.name);
});
// Transform the columns to CSV
for (row = 0; row < columns[0].length; row++) {
line = [];
for (col = 0; col < columns.length; col++) {
line.push(columns[col][row]);
}
csv += line.join(itemDelimiter) + lineDelimiter;
}
return csv;
};
}(Highcharts));
// Now we want to add "Download CSV" to the exporting menu. We post the CSV
// to a simple PHP script that returns it with a content-type header as a
// downloadable file.
// The source code for the PHP script can be viewed at
// https://raw.github.com/highslide-software/highcharts.com/master/studies/csv-export/csv.php
Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
text: 'Download CSV',
onclick: function () {
Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', {
csv: this.getCSV()
});
}
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
$('#getcsv').click(function () {
alert(chart.getCSV());
});
答案 1 :(得分:1)
您可以在HighCharts范围之外进行此操作。您可以随时提取series.data值,并通过它们迭代以在页面上的javascript中创建CSV。或者你可以在后端提前完成。
答案 2 :(得分:1)
您可以添加导出按钮(http://api.highcharts.com/highcharts#exporting.buttons.contextButton.onclick)并准备函数,该函数将从图表中获取所有值(保存在chart.series对象中)并推送到字符串/数组。然后你需要找到一个解决方案如何在javascript中“生成”文件,并用数组/字符串填充它。