【发布时间】:2018-07-05 05:37:37
【问题描述】:
我有一个 AJAX POST 请求以 JSON 数组的形式取回数据。 我想将此收到的 JSON 数据转换为 Excel 文件(不是 CSV)以供下载(单击按钮),请帮助。 JSON 数据的每个 JSON 行可能包含空白值和缺失字段。
我在客户端使用 Javascript 进行了尝试,但没有在 Java 服务器端尝试,在这种情况下,我将不得不在 AJAX 端点方法中使用 @Produces(MediaType.MULTIPART_FORM_DATA),这是我可以尝试的,但认为它很复杂.
a) AJAX 请求代码:
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) 从 AJAX POST 请求接收的 JSON 示例数据:
[
{
"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"
}
]
【问题讨论】:
-
你接受从 Java 后端生成 Excel 的答案吗?
-
当然,那也应该没问题。非常感谢。
标签: javascript json ajax excel type-conversion