Tuesday 13 December 2011

JSF+PrimeFaces: how to download Excel (with actionListener)

public void exportExcelActionListener(ActionEvent event) {
  try {
    String filename = "myexceltodownload.xls";
         
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/vnd.ms-excel");
      
    // http://stackoverflow.com/questions/3592058/how-to-send-byte-as-pdf-to-browser-in-java-web-application
    // attachment (pops up a "Save As" dialogue) or inline (let the web browser handle the display itself)
    externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\""+filename+"\"");
 
    getWorkbook().write(externalContext.getResponseOutputStream()); //get workbook
    facesContext.responseComplete(); //if I don't call responseComplete() => IllegalStateException
      
    return null; //remain on same page
  } catch(Exception e) {
    // handle exception...
    return null; //remain on same page
   }
}

  
    
  

Note: To experiment with the download commandbutton of primefaces...
Note: Strangely didn't work for me....

No comments:

Post a Comment