Download CSV file using JSF

I do not know how to load a CSV file. A CSV will be generated at runtime. Do I need to save the file in the tomcat WEB-INF directory first? I am using JSF 1.2.

By the way, what is the preferred JSF component for this kind of task?


Edit (05/05/2012 - 15:53)

I tried the solution BalusCindicated in its first link, but if I click on my commandButton, the contents of the file will be displayed on the web page. Maybe a problem with mimetype?

XHTML file:

<a4j:form>
    <a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" />
</a4j:form>

main bean:

    public String doDataExport() {

    try {
        export.downloadFile();  
    } catch (SurveyException e) {
        hasErrors = true;
    }
    return "";
}

Export- bean:

public void downloadFile() throws SurveyException {

    try {

        String filename = "analysis.csv";

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

        response.reset();
        response.setContentType("text/comma-separated-values");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        OutputStream output = response.getOutputStream();

        // writing just sample data
        List<String> strings = new ArrayList<String>();

        strings.add("filename" + ";" + "description" + "\n");
        strings.add(filename + ";" + "this is just a test" + "\n");

        for (String s : strings) {
            output.write(s.getBytes());
        }

        output.flush();
        output.close();

        fc.responseComplete();

    } catch (IOException e) {
        throw new SurveyException("an error occurred");
    }
}

Edit (05/05/2012 - 16:27)

I solved my problem. I have to use <h:commandButton>instead <a4j:commandButton>, and now it works!

+5
source share
2 answers

WEB-INF tomcat?

, HTTP, ExternalContext#getResponseOutputStream() , , , .

, :

:

List<List<Object>> csv = createItSomehow();
writeCsv(csv, ';', ec.getResponseOutputStream());

, jsf- ?

. <p:dataExporter> .

+4

JSF 2, .
.

, :

List<Object> report = new ArrayList<Object>(); // fill your arraylist with relevant data 
String filename = "report.csv";    
File file = new File(filename);
Writer output = new BufferedWriter(new FileWriter(file));
output.append("Column1");
output.append(",");
output.append("Column2");
output.append("\n");
//your data goes here, Replcae Object with your bean
for (Object row:report){
    output.append(row.field1);
    output.append(",");
    output.append(row.field2);
    output.append("\n");
}
output.flush();
output.close();
0

All Articles