Showing posts with label Download csv file in JSF 2. Show all posts
Showing posts with label Download csv file in JSF 2. Show all posts

Monday, June 20, 2016

Quick Solution: Download csv file in JSF 2

In xhtml file, I use primefaces command button. You can also use h:commandButton.

<h:form>
<p:commandButton  value="Download File" action="#{branchDownload.download}"
                                 ajax="false"         /> 

 </h:form>

In Managed Bean class, download() method is as follows:

@ManagedBean
@RequestScoped
public class BranchDownload {
// Your code

// download method
public void download()
    {
        String file_name =  "FILE.csv" ;
       
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec= fc.getExternalContext();
        ec.responseReset();
        ec.setResponseContentType("text/csv");
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\""+file_name + "\"");
       
        BufferedOutputStream csvOut;
        try {
            csvOut = new BufferedOutputStream(ec.getResponseOutputStream());
            BufferedWriter csvWriter = new BufferedWriter(new OutputStreamWriter(csvOut, "UTF-8"));
       
            csvWriter.append("1,2,3,4,5,6,7,8");
            csvWriter.append("\n");
            csvWriter.flush();

            csvWriter.append("One,2,Three,4,5,6,7,8");
            csvWriter.append("\n");
            csvWriter.flush();

            csvWriter.close();
            csvOut.close();
        } catch (IOException ex) {
            Logger.getLogger(BranchDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            fc.responseComplete();
        }
      
    }
// End download method

}