Output an Excel file from JAX-RS : Produces an excel(.xlsx) file and output is prompted to the user.
package com.homedepot.ta.wh.md.service;
import java.io.File;
import java.io.FileOutputStream;
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;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@Path("/excel")
//Output an Excel file from JAX-RS
public class excelgenerator {
@GET
// mime type for excel output
@Produces("application/vnd.ms-excel")
@Path("/get")
ResponseBuilder rb=null;
/*
* Method which generates an excel file
* Writes to an output stream
* Appends the file in a response
* Builds the response so as to produce an .xlsx file
*
*/
public Response getExcel() {
File file = new File("Excel.xlsx");
try{
Workbook wb = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream(file);
wb.write(fos);
fos.close();
rb = Response.ok((Object) file);
rb.header("Content-Disposition","attachment; filename=Excel.xlsx");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return rb.build();
}
}