Download excel file from JAX-RS
In JAX-RS, for excel file, annotate the method with @Produces("application/vnd.ms-excel")
:
- Put @Produces(“application/vnd.ms-excel”) on service method.
- Set “Content-Disposition” in Response header to prompt a download box.
1. Download Excel file in JAX-RS
Full example to download an excel file from JAX-RS.
import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path("/excel")
public class ExcelService {
private static final String FILE_PATH = "c:\\excel-file.xls";
@GET
@Path("/get")
@Produces("application/vnd.ms-excel")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=new-excel-file.xls");
return response.build();
}
}
2. Demo
Access this URI pattern : “/excel/get“.
Figure : Excel file “c:\\excel-file.xls” from server is prompted for user to download, with a new file name “new-excel-file.xls“
Download Source Code
Download it – JAX-RS-Download-Excel-File-Example.zip (6 KB)
Did anyone had success with calling this function from JQuery? Can you please share your insights?
how to post an excel file to service ?
with this i was able to create and download the file, but the excel file is not opening. seems its corrupted. Could you please share the write way of calling from client side.
can any one please tell how to call this from angularjs
$scope.resolve = function() {
var excelOutputDownloadUrl = ‘rest/download/excel’;
var fileName = $scope.layoutDisplay.name + ‘.xlsx’
var excelArr ={“fileName”:fileName, recordArr : []};
//excelArr.push()
for (var i = 0; i < $scope.layoutDisplay.fields.length; i++) {
var field = $scope.layoutDisplay.fields[i];
var tagFileName = $scope.getTagFileName(field);
excelArr.recordArr.push({
fieldName: field.fieldName,
fieldDescription: field.description,
fieldLength: field.fieldLength,
custom: (field.custom ? “true” : “false”),
formula: field.nameFormula,
tagFileId: (tagFileName && tagFileName != null ? field.dataFileField.dataFileId : null),
tagFileName: tagFileName,
repeatGroupName: field.repeatGroupName
});
}
$http.post(excelOutputDownloadUrl, excelArr, {
headers: { ‘Content-Type’: ‘application/json’ },
withCredentials: true
}).then(function(result) {
$log.info(‘report result: ‘, result);
$scope.buttonEnable = true;
});
I’m implementing end points as stateless ejbs, so I’m getting not serializable exception on BuiltResponse class. Any ideas? I’m using rest easy.
Can you please tell how can we integrate this service through Angular JS
can you please also write a Jersey client for this service? Thank you.
I tried a simple web service to try this out and it’s “working” (meaning the code isn’t blowing up) but the browser isn’t liking it. Here’s my code (using a later version of Spring and jersey):
@RequestMapping(value=”xls-test”, method = {RequestMethod.GET}, produces=”application/vnd.ms-excel”)
public @ResponseBody Response xlsTest(
Model model) {
try {
File file = new File(“/Users/Jeff/Desktop/test.xls”);
ResponseBuilder response = Response.ok((Object) file);
response.header(“Content-Disposition”,
“attachment; filename=”test.xls””);
LOG.debug(“File name = ” + file.getAbsolutePath());
return response.build();
} catch (Exception e) {
return null;
}
}
Hitting it with a browser produces:
HTTP Status 406 –
type Status report
message
description The
resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
“accept” headers ().
I’m not sure if it’s returning something poorly or I need something on the client side to expect an excel file.
Thanks for your help. mkyong – I use your stuff almost daily – you rock!
Jeff
Hey can you please let me know how you can call this rest service from Jquery/Javascript. I am doing an AJAX call but the data format returned isnt correct and it has a lot of spl characters.
When I fire the URL directly in the browser, it downloads the Excel file correctly.
$.ajax({
url:”../control/limitProfile/exportIntradayTradeList/” + gid
}
I am unable to open the apache poi xls in mac os preview
please help on this
sir,
i want to know how to create a simple soap webservice that return a xml file or a text file, using netbeans.
Hello,
I would like to know how download an excel file jax-rs with a query jpql
Hi,
Have written a similar Restful service using Jersey Framework to render xls file upon request. However am facing below problem while running the service url on a new IE tab [IE version 8]. We are using single-signon authentication mode. The first request gives us the excel report. However if open a new tab in the same IE window and request the URL, it craps out with below error
“Internet Explorer cannot download xxxx from server
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please tyr again later”
It works in all the other browsers except IE 8. Tried to add below to clear header, but of no avail. Request you to let know if there is anything we can do to avoid this problem
ResponseBuilder response = Response.ok(stream);
response.header(“Content-Disposition”,
“attachment; filename=new-excel-file.xls”);
response.header(“Pragma”, “no-cache”);
response.header(“Cache-Control”, “no-cache”);
response.header(“Cache-Control”, “max-age=0”);
response.header(“Expires”, “Thu, 01 Nov 2012 16:00:00 GMT”);
return response.build();
Do you have an example how to call it from java script or better jQuery. I can execute it directly from browser but not from web page.