In this article we will see how we can convert a data source compatible with Chartjs to an HTML table.
The function below accepts an object identical to the data that Chartjs wants. As you can see, there are two loops.
The first loop creates header of the table traversing the datasets
array. It also uses the fillColor
as a background color for each cell.
The second loop creates the body of the table traversing the labels
array. It also uses the fillColor
as a background color for each cell.
var dataToTable = function (dataset) { var html = '<table>'; html += '<tr> <th style="width:120px;">#</th>'; var columnCount = 0; jQuery.each(dataset.datasets, function (idx, item) { html += '<th style="background-color:' + item.fillColor + ';">' + item.label + '</th>'; columnCount += 1; }); jQuery.each(dataset.labels, function (idx, item) { html += '<tr><td>' + item + '</td>'; for (i = 0; i < columnCount; i++) { html += '<td style="background-color:' + dataset.datasets[i].fillColor.replace('0.5', '0.2') + ';">' + (dataset.datasets[i].data[idx] === '0' ? '-' : dataset.datasets[i].data[idx]) + '</td>'; } html += '</tr>'; //'<td></td>'; }); html += '</tr>'; html += '</table>'; return html; };
This jsfiddle has a simple demonstration of the above code
Tip: You can use this function to provide the HTML table as an excel download
var download = function (name, content, mimetype) { if ($('.download-trigger').length === 0) { jQuery('body').append('<span style="display:none;"><a class="download-trigger"></a></span>') } var a = $('.download-trigger')[0]; a.href = window.URL.createObjectURL(new Blob([content], { type: mimetype })); a.download = name; a.textContent = 'Download'; a.click(); };
download('file.xls', dataToTable(excelData), 'application/vnd.ms-excel');
Leave a Reply