2

I have charts generated via HighCharts through a WP AdCenter plugin. I want users (admins and subscribers alike) to be able to download the raw data driving the chart as Excel or CSV, not just a PNG, JPG or PDF image of the chart. Is there a way to do this without too serious a modification of the code (I'm not a PHP programmer). Is this additional export option a feature that could be rolled out in the near future?

4

3 回答 3

9

这个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());
});
于 2013-06-29T22:15:32.650 回答
1

您可以在 HighCharts 范围之外执行此操作。您可以随时提取 series.data 值并遍历它们以从页面上的 javascript 中生成 CSV。或者您可以在后端提前完成。

于 2013-05-14T16:22:39.133 回答
1

您可以添加导出按钮(http://api.highcharts.com/highcharts#exporting.buttons.contextButton.onclick)并准备函数,该函数将从图表中获取所有值(保存在 chart.series 对象中)并推送到字符串/数组. 然后你需要找到一个解决方案如何在javascript中“生成”文件,并用数组/字符串填充它。

于 2013-05-15T11:29:13.240 回答