0

I am trying to export the result set of the DB in a excel format. And I am developing a web application using JSF. So what i need is that when the user clicks on the EXPORT button in my page , then a file save dialog has to open for the user to choose the directory path and the name for the file.

And when the save is clicked in the file dialog then i need to write the whole result set to the excel sheet with the mentioned name and path as per users input.

But i couldnt find the file save dialog and how to use the same with JSF. And I am using jdeveloper for the development .

Please suggest me a solution.

Sundhar
  • 149
  • 1
  • 7
  • 21
  • Hint: [`Content-Disposition: attachment`](http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses) – Matt Ball Jan 13 '12 at 00:57

1 Answers1

4

The key is the Content-Disposition response header which you need to set to attachment. This will force a Save As dialogue in the browser. All you need to do along this is to set a proper Content-Type response header as well (so that the browser know what type of file it is) and to write the raw file's content to the response body.

So, summarized (assuming that you're using Apache POI to generate the Excel sheet):

public void downloadReport() throws IOException {
    // Prepare Excel file to be downloaded.
    HSSFWorkbook workbook = generateReportSomehow();
    String filename = "yourDefaultFilename.xls";

    // Prepare response.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/vnd.ms-excel");
    externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    // Write file to response body.
    workbook.write(externalContext.getResponseOutputStream());

    // Inform JSF that response is completed and it thus doesn't have to navigate.
    facesContext.responseComplete();
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555