highcharts自定义导出文件格式(csv) highcharts的一些使用心得
highcharts是国外的一个图表插件,包括各种数据图形展示,柱形图,线性图等等,是手机端和pc端最好的图表插件之一,相比于百度的echarts更加轻便和易懂。链接http://www.hcharts.cn/。之前的highcharts版本都是支持图表导出功能的,导出的可以为图片文件和pdf以及svg文件,为了更加方便地查看图表数据和分析数据,我们还是需要导出具体的series和categories数据,我们的想法是导出为excel文件或者csv文件,以上两者都可以直接用excel打开。
之前也有一篇借用浏览器的ActiveX插件来实现导出excel文件的文章:http://www.stepday.com/topic/?544 今天我们就来扩展一下highcharts如何直接导出csv格式的文件。
根据highcharts官方的扩展组件来看,我们需要下载导出csv的核心js文件:https://rawgithub.com/highslide-software/export-csv/master/export-csv.js 可以点击下载至本地也可以直接在自己的页面内引入,形如:
/** * 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'; } });
当我们加上exporting.js的时候下载选项菜单就出来了对吧,如图:
你们的应该是英文的,具体变成中文设置如下:
Highcharts.setOptions({
lang: {
printChart: "打印图表",
downloadJPEG: "下载JPEG 图片",
downloadPDF: "下载PDF文档",
downloadPNG: "下载PNG 图片",
downloadSVG: "下载SVG 矢量图",
exportButtonTitle: "导出图片",
downloadCSV:"下载CSV格式文件",
downloadXLS:"下载XLS格式文件"
}
});
这段代码是highcharts全区设置里放在$(document).ready({放这就行了});
这个Viewdata table很蛋疼,点击了显示没办法隐藏了。所以这里我们把它去掉,上面export_csv.js去掉红色关于viewdata的部分就行了,注释掉即可。
自定义下载按钮下载文件格式为csv:
解读它的插件js可以看到上面我标记为绿色的部分,这两行代码就是下载的执行代码。那我们直接可以调用就行了:
// 下载图表
$('.pr_li_1').click(function() {
if (index == 0) {
g_chart = $('#chart_C').highcharts(); //得到上面图表的对象
g_chart.downloadCSV();
}else if (index == 1) {
g2_chart = $('#LTV_chart').highcharts(); //得到上面图表的对象
g2_chart.downloadCSV();
}
});
这样就是点击按钮下载csv文档格式了,你也可以写成XLS格式的。
有的人是想简单的就是下载图片png或者img格式,那这个就是更改exporting.js了,具体操作很简单,查看官网的exporting就行了。
表格重绘:
有的人想要表格重新刷新或者重新绘制一下那种效果,可以用在table切换后,或者隐藏显示,刷新数据以后。这个很简单,调用一下就行了:chart1 = new Highcharts.Chart(chart);
上面那就要这么写:
chart = {
credits: {
text: null,
},
chart: {
// type: 'column',
renderTo: 'chart_C',
zoomType: 'xy',
// inverted: false
},
exporting: {
enabled: false
},......................略.
highcharts自定义导出文件格式(csv) highcharts的一些使用心得的更多相关文章
- Python使用Flask框架,结合Highchart,自定义导出菜单项目及顺序
参考链接: https://www.highcharts.com.cn/docs/export-module-overview https://api.hcharts.cn/highcharts#ex ...
- c#自带压缩类实现数据库表导出到CSV压缩文件的方法
在导出大量CSV数据的时候,常常体积较大,采用C#自带的压缩类,可以方便的实现该功能,并且压缩比例很高,该方法在我的开源工具DataPie中已经经过实践检验.我的上一篇博客<功能齐全.效率一流的 ...
- c#自带压缩类实现数据库表导出到CSV压缩文件
c#自带压缩类实现数据库表导出到CSV压缩文件的方法 在导出大量CSV数据的时候,常常体积较大,采用C#自带的压缩类,可以方便的实现该功能,并且压缩比例很高,该方法在我的开源工具DataPie中已经经 ...
- 将sqlserver导出的csv数据导入到ubuntu和mac上的mysql
最近在捣鼓一些数据相关的东西.将sql server里的数据导入到ubuntu和mac上的mysql,方法有很多.不过我选择了最简单的一种:将sql server的数据导成csv,然后将csv导入到m ...
- 网页图表Highcharts实践教程之认识Highcharts
网页图表Highcharts实践教程之认识Highcharts 认识Highcharts Highcharts是国际知名的一款图表插件.它完全使用Javascript编写实现.其结构清晰,使用简单.开 ...
- hadoop编程小技巧(5)---自定义输入文件格式类InputFormat
Hadoop代码测试环境:Hadoop2.4 应用:在对数据需要进行一定条件的过滤和简单处理的时候可以使用自定义输入文件格式类. Hadoop内置的输入文件格式类有: 1)FileInputForma ...
- 将mysql的查询结果导出为csv
要将mysql的查询结果导出为csv,一般会使用php连接mysql执行查询,将返回的查询结果使用php生成csv格式再导出. 但这样比较麻烦,需要服务器安装php才可以实现. 直接使用mysql导出 ...
- QTableWidget 导出到csv表格
跳槽到了新的公司,开始苦逼的出差现场开发,接触到了新的应用.有很多应用需要将Table导出成表格,可以把table导出成csv格式的文件.跟大伙分享一下: lass TableToExcle : pu ...
- java导出生成csv文件
首先我们需要对csv文件有基础的认识,csv文件类似excel,可以使用excel打开,但是csv文件的本质是逗号分隔的,对比如下图: txt中显示: 修改文件后缀为csv后显示如下: 在java中我 ...
随机推荐
- 解决Maven下载依赖慢
微服务spring boot,在使用maven下载依赖的时候非常慢,几十K的依赖JAR,也需要漫长的等待,更悲剧呢的漫长等待结果提示下载失败,为彻底解决这个问题,决定使用国内的镜像库,想象总是美好的, ...
- 洛谷 U14472 数据结构【比赛】 【差分数组 + 前缀和】
题目描述 蒟蒻Edt把这个问题交给了你 ---- 一个精通数据结构的大犇,由于是第一题,这个题没那么难.. edt 现在对于题目进行了如下的简化: 最开始的数组每个元素都是0 给出nnn,optopt ...
- BZOJ 4864: [BeiJing 2017 Wc]神秘物质 解题报告
4864: [BeiJing 2017 Wc]神秘物质 Description 21ZZ 年,冬. 小诚退休以后, 不知为何重新燃起了对物理学的兴趣. 他从研究所借了些实验仪器,整天研究各种微观粒子. ...
- 洛谷 P1325 雷达安装 解题报告
P1325 雷达安装 题目描述 描述: 假设海岸线是一条无限延伸的直线.它的一侧是陆地,另一侧是海洋.每一座小岛是在海面上的一个点.雷达必须安装在陆地上(包括海岸线),并且每个雷达都有相同的扫描范围d ...
- 模块(3)-使用__future__
使用__future__ Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动.有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了. 从Pyt ...
- bzoj4165: 矩阵(堆+hash)
求第k大用堆维护最值并出堆的时候扩展的经典题... 因为只有正数,所以一个矩阵的权值肯定比它的任意子矩阵的权值大,那么一开始把所有满足条件的最小矩阵加进堆里,弹出的时候上下左右扩展一行加进堆,用has ...
- opencv透视变换GetPerspectiveTransform的总结
对于透视变换,必须为map_matrix分配一个3x3数组,除了3x3矩阵和三个控点变为四个控点外,透视变化在其他方面与仿射变换完全类似.具体可以参考:点击打开链接 主要用到两个函数WarpPersp ...
- libuv移植到android
编译环境是linux + ndk,你要先添加好NDK路径的环境变量,然后进入libuv目录执行以下两句完成编译. $ source ./android-configure $NDK gyp $ mak ...
- java学习——equals()和==的比较
equals 方法是 java.lang.Object 类的方法. 下面从两个方面来说明equals()和==的差别:(1)对于字符串变量来说,使用“==”和“equals()”方法比较字符串时,其比 ...
- [Mac]一些命令技巧
Git相关 mac下git默认不区分大小写,通过下面脚本可以改变 #!/bin/bash # 让git区分大小写 cd 'path-of-project' git config core.ignore ...