Search code examples
exceljakarta-eestruts2strutsapache-poi

Dynamic file download without saving file in the server


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


Solution

  • 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;
    }