Exporting Chart Data to Excel - Kendo UI Chart
Environment
Product | Version |
---|---|
Progress® Kendo UI® Chart for jQuery | 2023.3.1114 |
Description
I want to be able to export data from a Kendo UI Chart to Excel. How can I achieve this?
Solution
You can implement the export to Excel functionality for a Kendo UI Chart by following these steps:
- Reference the Kendo UI Chart and DataSource.
- Define the column headers in a rows array.
- Get the Chart's DataSource data, and push it to the rows array.
- Define a Kendo UI ooxml.Workbook and include the rows.
- Use the Kendo.saveAs method to save the Excel file with the data.
Here is an example of how to achieve this using JavaScript:
<button id="exportButton">Export to Excel</button>
<div id="chart"></div>
<script>
$("#chart").kendoChart({
dataSource: {
transport: {
read: {
url: "https://demos.telerik.com/kendo-ui/content/dataviz/js/spain-electricity.json",
dataType: "json"
}
},
sort: {
field: "year",
dir: "asc"
}
},
title: {
text: "Spain electricity production (GWh)"
},
legend: {
position: "top"
},
seriesDefaults: {
type: "column"
},
series:
[{
field: "nuclear",
categoryField: "year",
name: "Nuclear"
}, {
field: "hydro",
categoryField: "year",
name: "Hydro"
}, {
field: "wind",
categoryField: "year",
name: "Wind"
}],
categoryAxis: {
labels: {
rotation: -90
},
majorGridLines: {
visible: false
}
},
valueAxis: {
labels: {
format: "N0"
},
majorUnit: 10000,
line: {
visible: false
}
},
tooltip: {
visible: true,
format: "N0"
}
});
$("#exportButton").kendoButton({
click: function(e){
// Reference Chart
let chart = $("#chart").data("kendoChart");
// Reference Chart DataSource
let chartDataSource = chart.dataSource;
// Define Column Headers
let rows = [{
cells: [
{ value: "Year" },
{ value: "Nuclear" },
{ value: "Hydro" },
{ value: "Wind" }
]
}];
// Get DataSource Data
let data = chartDataSource.data();
for (var i = 0; i < data.length; i++){
// Push single row for every record.
rows.push({
cells: [
{ value: data[i].year },
{ value: data[i].nuclear },
{ value: data[i].hydro },
{ value: data[i].wind }
]
})
}
// Define Workbook
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
// Column settings (width).
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
// The title of the sheet.
title: "Chart Title",
// The rows of the sheet.
rows: rows
}
]
});
workbook.toDataURLAsync().then(function(dataURL) {
kendo.saveAs({
dataURI: dataURL,
fileName: "Test.xlsx"
});
});
}
});
</script>
Please refer to this Progress Kendo UI Dojo for a live example demonstrating this approach.