I have some data from JQGrid that should be exported to excel. So, we have written a java servlet to write the data to excel and send it back. From the client side we are using an AJAX JSONP request by sending JSON data. I am able to hit the servlet and servlet sending the created excel back to the client. But i am not able to see excel or any kind of output from client side.
When i use the Fiddler and observed the http calls, i found that application received the result. but still it is not showing the result.
Here is my result header, that i have received.
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=PistonData.xls
Content-Type: application/vnd.ms-excel
Content-Length: 6144
Date: Tue, 27 Mar 2012 08:49:04 GMT
How to open this result as Excel using JQuery? Can somebody please suggest me a way to fix this issue.
Update #1
Forgot to include request
$.ajax({
type: "POST",
dataType: "jsonp",
contentType:'application/vnd.ms-excel',
url: "http://devmachine:9010/axis/SPSServlet",
data: param,
success: function (dataToSend) {
alert(dataToSend);
}
});
Update #2
As per Oleg’s suggestions i worked out a solution for this problem.
Here is my code:
<form id="frmExcelExport" style="display:none;">
<input type=hidden id="partId" name="partId" />
<input type=hidden id="columnNames" name="columnNames" />
<input type=hidden id="data" name="data" />
</form>
$('#columnNames').val(colModStr);
$('#partId').val(currentPartID);
$('#data').val(dataStr);
var urlForExport = "http://devmachine:9010/axis/SPSServlet";
$('#frmExcelExport').attr("method", "post");
$('#frmExcelExport').attr("action", urlForExport);
$('#frmExcelExport').submit();
and it is working very good.
Thanks a bunch to Oleg!!!!
I think that you can’t open Excel if you use HTTP
POST. The way which will work is to use HTTPGETand encode parameters which you need in the URL:In the way the web browser will opens the returned data as
PistonData.xlsspecified inContent-Dispositionheader with respect of the application registered forapplication/vnd.ms-excel(seeContent-Typeheader). See the answer for more details.If you need to prevent uncontrolled caching of the XLS data returned from the server I would recommend you to set additional HTTP header
"Cache-Control: max-age=0"or better"Cache-Control: private, max-age=0"to prevent caching without re-validation on the HTTP proxy. See here, here for additional information.