I am looking for help with converting JSON data received from an AJAX POST Request into an Excel file (not CSV) for download on a button click. The JSON Data may contain blank values and missing fields for each JSON row.
I have attempted to achieve this on the client side using Javascript, but I am now considering exploring server-side Java implementation where I would need to use @Produces(MediaType.MULTIPART_FORM_DATA) in the AJAX Endpoint method. This approach seems complex, but it's something worth trying.
a) Here is the code snippet for the AJAX request:
function fileUploadFunction() {
var file = $('input[name="file"]').get(0).files[0];
var formData = new FormData();
if(file.name != null) {
document.getElementById("btnUpload").disabled = false;
formData.append('file', file);
$.ajax({
url : "<%=request.getContextPath()%>/rest/upload/upload",
type : "POST",
data : formData,
cache : false,
contentType : false,
processData : false,
success : function(response) {
//Store result in Session and Enable Download button
var cacheString = JSON.stringify(response, null, 2);
console.log("-----------------> cacheString is: " + cacheString);
if(cacheString != null && cacheString != "[]") {
document.getElementById("download").disabled = false;
}
var sessionresponse = sessionStorage.setItem("i98779", cacheString);
console.log("response is: " + response);
console.log("cacheString is: " + cacheString);
excelDownload(cacheString);
//createTable(response);
//https://stackoverflow.com/questions/47330520/how-to-export-json-object-into-excel-using-javascript-or-jquery
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
alert("Error: " + errorThrown);
}
});//ajax ends
}//if ends
}//Function ends
b) Below is a sample of JSON data received from the AJAX POST Request:
[
{
"entityid":2,
"firstname":"George",
"lastname":"Bush",
"ssn":"",
"city":"Houston",
"state":"TX",
"country":"USA",
"zipcode":""
},
{
"entityid": 8,
"firstname": "Jim",
"lastname": "Macron",
"ssn": "888-88-8888",
"city": "Paris",
"state": "NY",
"country": "France",
"zipcode": "T789J"
},
{
"entityid": 11,
"firstname": "Angela",
"lastname": "Merkel",
"city": "Saxony",
"zipcode": ""
},
{
"entityid": 7,
"firstname": "Donald",
"lastname": "Trump",
"ssn": "777-77-7777",
"city": "Washington D.C.",
"state": "DC",
"country": "USA",
"zipcode": "70000"
}
]