3

I am using Apache POI libraries to do some operation on multiple excel files.

I'm trying to download the excel report without storing it somewhere in the server.

I am using Struts 2 which needs the file fed into a InputStream while POI Workbook needs a OutputStream to write the data into.

Any help would be great

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Anup Sahu
  • 93
  • 1
  • 6

2 Answers2

3

Since you already know you need a Stream result:

I am using Struts 2 which needs the file fed into a InputStream

// With Getter
private InputStream inputStream;

and you already know how to create an Excel with POI:

POI Workbook needs a OutputStream to write the data into.

public String execute(){

    // stuff 

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // fill the OutputStream with the Excel content
    workbook.write(baos);

then the only missing piece is how to convert the POI's OutputStream into the Struts2 Stream result's InputStream. And this is easier than the rest..:

    // Create an Input Stream from the bytes extracted by the OutputStream
    inputStream = new ByteArrayInputStream(baos.toByteArray());

    return SUCCESS;
}
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
0

This is how done it.

@RequestMapping(value = "/report/generate", method = RequestMethod.GET)
public ResponseEntity download(HttpServletResponse response) throws IOException {

        //..code to create your excel here using poi
        
        //Write data to outputstream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);

        if(workbook != null && outputStream != null) {
            workbook.close();
            outputStream.close();
        }

        //get bytes
        byte[] documentContent = outputStream.toByteArray();
        //prepare header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"report.xlsx\"");
        headers.setContentLength(documentContent.length);
        return new ResponseEntity(documentContent, headers, HttpStatus.OK);
}
VK321
  • 5,768
  • 3
  • 44
  • 47