Download excel file from JAX-RS

In this tutorial we will discuss about download ms excel files from JAX-RS, for user to download a file, annotate the method with @Produces("application/vnd.ms-excel") :
  1. Put @Produces("application/vnd.ms-excel") on service method, with a Response return type. It means the output is a ms excel file.
  2. Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.
1. Download Excel file in JAX-RS

Full example to download an ms excel file from JAX-RS.

package com.dineshonjava.ws.rest;

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;

 * @author Dinesh Rajput
public class ExcelFileService {
 private static final String EXCEL_PATH = "d:\\Contact.xls";
 public Response getContactExcelFile() {
  File file = new File(EXCEL_PATH);
  ResponseBuilder response = Response.ok((Object) file);
   "attachment; filename=\"contact_excel_file.xls\"");
  return response.build();

2. Test

Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/excel/get".

Figure : MS-Excel file "d:\\Contact.xls" from server is prompt for user to download, with a new me excel file name "contact_excel_file.xls"

Download excel file from JAX-RS

Download SourceCode
Download excel file from JAX-RS.zip

1. JAVA REST Web Services
2. Wikipedia for REST Web Service


<<Previous <<   || Index ||   >>Next >>