HorseFace
HorseFace

Reputation: 385

Create excel in Resteasy

I would like to create/return an excel file from my RestEasy webservice but am having some trouble getting it to work. When i run the code below (pseudo code) I get the following error:

org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: java.io.FileOutputStream of media type: application/vnd.ms-excel

Here is some code

@POST
@Path("/exportMyData")
@Produces("application/vnd.ms-excel")
public Response getMyData(@FormParam("id") String id) {
    HSSFWorkbook hwb = new HSSFWorkbook();
    ResponseBuilder response = null;
    try{
        List<Alert> alertList= service.getAlerts(id);


        HSSFSheet sheet =  hwb.createSheet("new sheet");

        HSSFRow rowhead=   sheet.createRow((short)0);
        rowhead.createCell((int) 0).setCellValue("ID");
        rowhead.createCell((int) 1).setCellValue("Name");
        rowhead.createCell((int) 2).setCellValue("Age");


        for(Alert alert : alertList){
            HSSFRow row=   sheet.createRow((short)1);
            row.createCell((int) 0).setCellValue(alert.getId());
            row.createCell((int) 1).setCellValue(alert.getName());
            row.createCell((int) 2).setCellValue(alert.getAge());
        }


        FileOutputStream fos = new FileOutputStream("mystream.xls");
        hwb.write(fos);
        response = Response.ok(fos);            
        response.header("Content-disposition","attachment; filename=export.xls");
    }catch(Exception e){

    }

    return response.build();
}

Any ideas? Thanks in advance /Eric

Upvotes: 6

Views: 3525

Answers (3)

gustavohenke
gustavohenke

Reputation: 41440

I've found that if you do the following, it'll work:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
hwb.write(baos);
response = Response.ok(baos.toByteArray());
response.header("Content-disposition", "attachment; filename=export.xls");

Upvotes: 8

wwj
wwj

Reputation: 123

You need to create the custom mediaType using the MessageBodyWriter/MessageBodyReader interface. Please refer to this (How to handle/create new content-type/MediaType in JAX-RS?).

Upvotes: 0

donramos
donramos

Reputation: 534

Your requirement of returning Excel does not require RestEasy. You can do this using plain old servlets.

RestEasy is for implementing REST services that return XML, JSON or plain text. @Produces does not support "application/vnd.ms-excel".

Upvotes: 0

Related Questions