问题
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!!!!
回答1:
I think that you can't open Excel if you use HTTP POST
. The way which will work is to use HTTP GET
and encode parameters which you need in the URL:
window.location = "http://devmachine:9010/axis/StdPartSearchServlet?" +
$.param({someParamName: "someValue", anotherParam: 123});
In the way the web browser will opens the returned data as PistonData.xls
specified in Content-Disposition
header with respect of the application registered for application/vnd.ms-excel
(see Content-Type
header). 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.
回答2:
If you are trying to use jquery to download the file, maybe you should look here:
http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads 1
This has a working snippet to do what you want.
来源:https://stackoverflow.com/questions/9886308/jquery-excel-export-issue