Download excel file from JAX-RS

In JAX-RS, for excel file, annotate the method with @Produces("application/vnd.ms-excel") :
  1. Put @Produces(“application/vnd.ms-excel”) on service method.
  2. 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

Komentar