To enable export to Excel, JSONCSVConverter can be utilized with the following steps:
- Include the JSONtoCSVConverter JavaScript file.
- Prepare the JSON data.
- Use Jquery library.
This specific line plays a crucial role: JSONToCSVConvertor(data, "Blog Report", true);
Explanation of parameters:
1st parameter - Data input
2nd parameter - File name specification
3rd parameter - Label inclusion condition
For more details and guidance, refer to the resources below:
Blog
Plunker
<!DOCTYPE html>
<html>
<head>
<title>Internet explorer download</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<div align="center">
<h3><u>Enter JSON data</u></h3>
<div class="mydiv">
<textarea cols="100" rows="15" class="txtarea" id="txt">[{"Blog Name":"PrathapKudupusBlog","Date":"30 Jul 2013 09:24 AM","Type":"Technical","Author"
:"Prathap Kudupu"},
{"Blog Name":"ABCBlog","Date":"30 Jul 2011 09:24 AM","Type":"Technical","Author"
:"ABC"},
{"Blog Name":"XYZBlog","Date":"30 Jul 2011 09:24 AM","Type":"Technical","Author"
:"XYZ"}]</textarea> <br>
<h3><u>Click below button to download <strong>CSV</strong> file for internet explorer and other browsers</u></h3>
<br>
<button class="download">Download CSV</button>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "Blog report", true);
});
});
function JSONToCSVConvertor(JSONData,title, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
var arrValue = arrData[i][index] == null ? "" : '="' + arrData[i][index] + '"';
row += arrValue + ',';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
growl.error("Invalid data");
return;
}
var fileName = title;
if (msieversion()) {
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
} else {
var uri = 'data:application/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
function msieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie != -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
return true;
} else { // If another browser,
return false;
}
}
</script>