1. 程式人生 > >highcharts自定義匯出檔案格式(csv) highcharts的一些使用心得

highcharts自定義匯出檔案格式(csv) highcharts的一些使用心得

/**
 * A Highcharts plugin for exporting data from a rendered chart as CSV, XLS or HTML table
 *
 * Author:   Torstein Honsi
 * Licence:  MIT
 * Version:  1.4.2
 */
/*global Highcharts, window, document, Blob */
(function (factory) {
    if (typeof module === 'object' && module.exports) {
        module.exports = factory;
    } else {
        factory(Highcharts);
    }
})(function (Highcharts) {

    'use strict';

    var each = Highcharts.each,
        pick = Highcharts.pick,
        seriesTypes = Highcharts.seriesTypes,
        downloadAttrSupported = document.createElement('a').download !== undefined;

    Highcharts.setOptions({
        lang: {
            downloadCSV: 'Download CSV',
            downloadXLS: 'Download XLS',
            viewData: 'View data table'
        }
    });


    /**
     * Get the data rows as a two dimensional array
     */
    Highcharts.Chart.prototype.getDataRows = function () {
        var options = (this.options.exporting || {}).csv || {},
            xAxis = this.xAxis[0],
            rows = {},
            rowArr = [],
            dataRows,
            names = [],
            i,
            x,
            xTitle = xAxis.options.title && xAxis.options.title.text,

            // Options
            dateFormat = options.dateFormat || '%Y-%m-%d %H:%M:%S',
            columnHeaderFormatter = options.columnHeaderFormatter || function (series, key, keyLength) {
                return series.name + (keyLength > 1 ? ' ('+ key + ')' : '');
            };

        // Loop the series and index values
        i = 0;
        each(this.series, function (series) {
            var keys = series.options.keys,
                pointArrayMap = keys || series.pointArrayMap || ['y'],
                valueCount = pointArrayMap.length,
                requireSorting = series.requireSorting,
                categoryMap = {},
                j;

            // Map the categories for value axes
            each(pointArrayMap, function (prop) {
                categoryMap[prop] = (series[prop + 'Axis'] && series[prop + 'Axis'].categories) || [];
            });

            if (series.options.includeInCSVExport !== false && series.visible !== false) { // #55
                j = 0;
                while (j < valueCount) {
                    names.push(columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length));
                    j = j + 1;
                }

                each(series.points, function (point, pIdx) {
                    var key = requireSorting ? point.x : pIdx,
                        prop,
                        val;

                    j = 0;

                    if (!rows[key]) {
                        rows[key] = [];
                    }
                    rows[key].x = point.x;

                    // Pies, funnels, geo maps etc. use point name in X row
                    if (!series.xAxis || series.exportKey === 'name') {
                        rows[key].name = point.name;
                    }

                    while (j < valueCount) {
                        prop = pointArrayMap[j]; // y, z etc
                        val = point[prop];
                        rows[key][i + j] = pick(categoryMap[prop][val], val); // Pick a Y axis category if present
                        j = j + 1;
                    }

                });
                i = i + j;
            }
        });

        // Make a sortable array
        for (x in rows) {
            if (rows.hasOwnProperty(x)) {
                rowArr.push(rows[x]);
            }
        }
        // Sort it by X values
        rowArr.sort(function (a, b) {
            return a.x - b.x;
        });

        // Add header row
        if (!xTitle) {
            xTitle = xAxis.isDatetimeAxis ? 'DateTime' : 'Category';
        }
        dataRows = [[xTitle].concat(names)];

        // Add the category column
        each(rowArr, function (row) {

            var category = row.name;
            if (!category) {
                if (xAxis.isDatetimeAxis) {
                    if (row.x instanceof Date) {
                        row.x = row.x.getTime();
                    }
                    category = Highcharts.dateFormat(dateFormat, row.x);
                } else if (xAxis.categories) {
                    category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x)
                } else {
                    category = row.x;
                }
            }

            // Add the X/date/category
            row.unshift(category);
            dataRows.push(row);
        });

        return dataRows;
    };

    /**
     * Get a CSV string
     */
    Highcharts.Chart.prototype.getCSV = function (useLocalDecimalPoint) {
        var csv = '',
            rows = this.getDataRows(),
            options = (this.options.exporting || {}).csv || {},
            itemDelimiter = options.itemDelimiter || ',', // use ';' for direct import to Excel
            lineDelimiter = options.lineDelimiter || '\n'; // '\n' isn't working with the js csv data extraction

        // Transform the rows to CSV
        each(rows, function (row, i) {
            var val = '',
                j = row.length,
                n = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.';
            while (j--) {
                val = row[j];
                if (typeof val === "string") {
                    val = '"' + val + '"';
                }
                if (typeof val === 'number') {
                    if (n === ',') {
                        val = val.toString().replace(".", ",");
                    }
                }
                row[j] = val;
            }
            // Add the values
            csv += row.join(itemDelimiter);

            // Add the line delimiter
            if (i < rows.length - 1) {
                csv += lineDelimiter;
            }
        });
        return csv;
    };

    /**
     * Build a HTML table with the data
     */
    Highcharts.Chart.prototype.getTable = function (useLocalDecimalPoint) {
        var html = '<table>',
            rows = this.getDataRows();

        // Transform the rows to HTML
        each(rows, function (row, i) {
            var tag = i ? 'td' : 'th',
                val,
                j,
                n = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.';

            html += '<tr>';
            for (j = 0; j < row.length; j = j + 1) {
                val = row[j];
                // Add the cell
                if (typeof val === 'number') {
                    val = val.toString();
                    if (n === ',') {
                        val = val.replace('.', n);
                    }
                    html += '<' + tag + ' class="number">' + val + '</' + tag + '>';

                } else {
                    html += '<' + tag + '>' + (val === undefined ? '' : val) + '</' + tag + '>';
                }
            }

            html += '</tr>';
        });
        html += '</table>';
        return html;
    };

    function getContent(chart, href, extension, content, MIME) {
        var a,
            blobObject,
            name,
            options = (chart.options.exporting || {}).csv || {},
            url = options.url || 'http://www.highcharts.com/studies/csv-export/download.php';

        if (chart.options.exporting.filename) {
            name = chart.options.exporting.filename;
        } else if (chart.title) {
            name = chart.title.textStr.replace(/ /g, '-').toLowerCase();
        } else {
            name = 'chart';
        }

        // MS specific. Check this first because of bug with Edge (#76)
        if (window.Blob && window.navigator.msSaveOrOpenBlob) {
            // Falls to msSaveOrOpenBlob if download attribute is not supported
            blobObject = new Blob([content]);
            window.navigator.msSaveOrOpenBlob(blobObject, name + '.' + extension);

        // Download attribute supported
        } else if (downloadAttrSupported) {
            a = document.createElement('a');
            a.href = href;
            a.target = '_blank';
            a.download = name + '.' + extension;
            document.body.appendChild(a);
            a.click();
            a.remove();

        } else {
            // Fall back to server side handling
            Highcharts.post(url, {
                data: content,
                type: MIME,
                extension: extension
            });
        }
    }

    /**
     * Call this on click of 'Download CSV' button
     */
    Highcharts.Chart.prototype.downloadCSV = function () {
        var csv = this.getCSV(true);
        getContent(
            this,
            'data:text/csv,\uFEFF' + csv.replace(/\n/g, '%0A'),
            'csv',
            csv,
            'text/csv'
        );
    };

    /**
     * Call this on click of 'Download XLS' button
     */
    Highcharts.Chart.prototype.downloadXLS = function () {
        var uri = 'data:application/vnd.ms-excel;base64,',
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">' +
                '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>' +
                '<x:Name>Ark1</x:Name>' +
                '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->' +
                '<style>td{border:none;font-family: Calibri, sans-serif;} .number{mso-number-format:"0.00";}</style>' +
                '<meta name=ProgId content=Excel.Sheet>' +
                '<meta charset=UTF-8>' +
                '</head><body>' +
                this.getTable(true) +
                '</body></html>',
            base64 = function (s) { 
                return window.btoa(unescape(encodeURIComponent(s))); // #50
            };
        getContent(
            this,
            uri + base64(template),
            'xls',
            template,
            'application/vnd.ms-excel'
        );
    };

    /**
     * View the data in a table below the chart
     */
    Highcharts.Chart.prototype.viewData = function () {
        if (!this.insertedTable) {
            var div = document.createElement('div');
            div.className = 'highcharts-data-table';
            // Insert after the chart container
            this.renderTo.parentNode.insertBefore(div, this.renderTo.nextSibling);
            div.innerHTML = this.getTable();
            this.insertedTable = true;
        }
    };
// Add "Download CSV" to the exporting menu. Use download attribute if supported, else // run a simple PHP script that returns a 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 if (Highcharts.getOptions().exporting) { Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({ textKey: 'downloadCSV', onclick: function () { this.downloadCSV()
; } }, { textKey: 'downloadXLS', onclick: function () { this.downloadXLS(); } }, { textKey: 'viewData', onclick: function () { this.viewData(); } }); } // Series specific if (seriesTypes.map) { seriesTypes.map.prototype.exportKey = 'name'; } if (seriesTypes.mapbubble) { seriesTypes.mapbubble.prototype.exportKey = 'name'; } });

相關推薦

highcharts定義匯出檔案格式(csv) highcharts一些使用心得

/** * A Highcharts plugin for exporting data from a rendered chart as CSV, XLS or HTML table * * Author: Torstein Honsi * Licence: MIT * Ver

hadoop程式設計小技巧(5)---定義輸入檔案格式類InputFormat

Hadoop程式碼測試環境:Hadoop2.4應用:在對資料需要進行一定條件的過濾和簡單處理的時候可以使用自定義輸入檔案格式類。Hadoop內建的輸入檔案格式類有:1)FileInputFormat<K,V>這個是基本的父類,我們自定義就直接使用它作為父類;2)T

ATS 4.2.3定義日誌檔案格式的方法

我只是總結歸納了別人的方法,並做了實際驗證,在這裡記錄一下,以備大家參考,向參考文獻中的各位前輩致敬。 ATS預設的日誌格式是squid.log,我們可以在/var/log/trafficserver目錄下面使用下面的命令檢視 traffic_logcat -f squid

定義Hive檔案和記錄格式(十)

create table 語句中預設的是stored as textfile       練習了store as sequencefile,省空間,提升i/o效能       PIG中輸入輸出分隔符預設是製表符\t,而到了hive中

HighCharts定義座標軸顯示內容

要繪製一個這樣的圖(如下圖):Y軸為數量,X軸為時間,大約240個值,那麼此時,X軸不可能完全顯示,只選擇整點來顯示。所以這裡需要自定義X軸的顯示 直接看程式碼: <div id="stock_img" style="width:560px;"></di

Django restframwork實現定義數據格式的分頁與搜索

模糊 ces none ota ntp model 簡單的 api ner 最近因為在做分頁時遇到的問題很多,頁浪費了好多時間,所以記錄一下。以後如遇到可用省去不必要的麻煩 restframwork中的官方文檔對分頁和搜索頁進行了詳細的介紹,但是我公司需要的return的

Vue定義時間日期格式將毫秒數轉化為‘yyyy-MM-dd hh:mm:ss’

 新建 filter 資料夾,在filter新建index.js,建立全域性過濾器 //filter/index.js內容 import Vue from 'vue' Vue.filter('date', function (dateTime, fmt) { var d

minigui:定義字型檔案的安裝位置(install location for custom font)

我們的基於minigui的嵌入式系統專案中使用了True Type字型,原以以為只要把字型檔案應用程式所在路徑下的字型資料夾(res/font)下就可以了,但實際執行時報錯了: NEWGAL>PCXVFB: /usr/local/bin/gvfb 12695 miniStudi

Fiddler開發實踐之定義匯出外掛

一、準備工作 1.安裝fiddler4; 2.vs2010以上(下方演示截圖都是基於vs2015的); 3.開啟fiddler debug相關功能; 在下圖位置輸入如下內容: 顯示錯誤和異常資訊: prefs set fiddler.debug.extensions.showerro

Springboot讀取配置檔案、pom檔案定義配置檔案

前言 很多人都知道讀取配置檔案,這是初級做法,上升一點難度是使用java bean的方式讀取自定義配置檔案,但是大家很少有知道讀取pom檔案資訊,接下來我都會講到。 正文 筆者還是基於Spring Boot ::        (v1.5.8.RE

Centos7上新增定義服務檔案並開機啟動

Ⅰ-1 寫服務檔案 [Unit]   ##服務的說明Description:描述服務After:描述服務類別 [Service]   ##服務執行引數的設定Type=forking是後臺執行的形式ExecStart為服務的具體執行命令ExecReload為重啟命令E

Android studio 使用定義mk檔案編譯jni專案

最近將公司ndk專案從eclipse遷移到as,為了方便省事,直接使用原有mk檔案。參考網路資料,順利完成遷移工作。現貼出使用自定義mk檔案的關鍵程式碼,mark以備後面使用。 buildTypes { release { minifyEna

總想自己動動手系列·1·本地和外網(Liunx伺服器上部署的web專案)按照定義的報文格式進行互動(一)

一、準備工作 (1)有一臺屬於自己的雲伺服器,併成功部署和釋出一個web專案(當然,本質上來說Java-Project也沒問題),通過外網IP可以正常訪問該web專案。   需要說明的是:任何web專案,只要成功部署後在外網上能訪問到即可。本案例注重修改web對請求的監聽和過濾的處

Java類載入器( CLassLoader ) 死磕5: 定義一個檔案系統的classLoader

【正文】Java類載入器(  CLassLoader ) 死磕5:  自定義一個檔案系統classLoader 本小節目錄 5.1. 自定義類載入器的基本流程 5.2. 入門案例:自定義檔案系統類載入器 5.3. 案例的環境配置 5.4 FileClassLoader 案例實現步驟 5

spring boot 讀取定義properties檔案

@Configuration@Componentpublic class PropertiesConfig { private static final String[] properties = {"/application.properties"}; private static Proper

laravel-admin 定義匯出excel功能,並匯出圖片

https://www.jianshu.com/p/91975f66427d 最近用laravel-admin在做一個小專案,其中用到了excel匯出功能。 但是laravel-admin自帶的匯出功能不帶圖片,並且匯出的資料有很多冗餘的欄位,並非我所需要的功能。 所以參考官方文件

js將一串隨機數字每四位加一個定義符號(格式:1234-5678-90)

方法一:      let string = '1234567890',result = '', index = 0; for(let i=0; i<string.length; i++){      result +=

【轉載】Smartforms 設定 定義紙張列印格式

在sap做一個列印報表,要先設定一個紙張列印格式,下面以工廠中常用來列印的針孔紙為例,在sap設定該紙張的列印格式,以用於報表: 1、執行事務程式碼SPAD;選擇工具欄上的【完全管理】按鈕——>選擇【裝置型別】頁面(在該頁面上有四個按鈕:【裝置型別】、【列印控制】、【格式型別】、【頁格式】

Android 定義型別檔案與程式關聯

0x01 功能  實現在其他應用中開啟某個字尾名的檔案 可以直接跳轉到本應用中的某個activity進行處理   0x01 實現    首先建立一個activity ,然後在manifest裡對該activity項編輯,加入    <intent-

springboot---讀取定義配置檔案

讀取自定義配置檔案 在有些時候,我們要配置一些資料,地址,路徑等操作,比如,上傳檔案的地址,新老路徑的定義,白名單介面等,這個時候需要在配置檔案裡面進行配置,而不是寫在程式碼裡面,在springboot裡面可以使用註解和實體兩種方式進行獲取到配置檔案裡面的配置資訊,我的做法是建立一個class,