1

I'm trying to implement downloading a dynamically created Excel spreadsheet, made with Apache POI. In JSF I'm using PrimeFaces, but for some reason I can't get it work with their FileDownload method. I've tried a few other things, but nothing seems to work for me.

This is currently my whole method:

public void generateExcel() throws IOException, InvalidFormatException {

    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) ec.getResponse();

    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "Spreadsheet.xls" + "\"");
    OutputStream output = response.getOutputStream();

    Workbook excelTabela = new HSSFWorkbook();

    //Building the xls content here.

    excelTabela.write(output);
    excelTabela.close();

    fc.responseComplete();
    output.flush();
    output.close();
}

It runs through this block of code (I checked with print statements) but nothing happens at all.

And this is the button I use for running this method:

<h:form>
    <p:remoteCommand name="gen" actionListener="#{PrevoziGeneratorBean.generateExcel}" />
    <h:commandButton type="button" onclick="gen()" value="Execute" />
</h:form>

I wrote this code based on the answer to this question but I can't get it to work.

Bombara
  • 41
  • 2
  • 5
  • 1
    "but I can't get it to work" show what you have tried and what exactly is not working for you. If possible (you did not mention versions), try with a newer version of JSF. – Jasper de Vries Sep 26 '18 at 11:34
  • I'm sorry for a bad question, I edited it to include my whole method and the button to run it. As I said in the question, the code runs which I checked with print statements but it doesn't do anything. – Bombara Sep 26 '18 at 12:08
  • _"the code runs which I checked with print statements but it doesn't do anything."_ sort of contradictory... – Kukeltje Sep 26 '18 at 12:29
  • Well it prints my statements into the console, so I know it makes it through, but it doesn't work in the sense that nothing else happens (I want it to download the excel file). Also I didn't include the print statements in the code above, because they are irrelevant. – Bombara Sep 26 '18 at 12:31
  • Don't do this with a remote command! Just use an action in the command button to generate and download the file and make sure no Ajax is used. – Jasper de Vries Sep 26 '18 at 12:46
  • That worked! Thank you for your patience and an excellent answer. – Bombara Sep 26 '18 at 13:02

0 Answers0