0

I'm using the apache.commons.csv library in Java to generate CSV and make it downloadable without storing on server using following code:

try (OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream())){
        csvWriter = new CSVPrinter(osw,CSVFormat.DEFAULT);

        writer.printRecord(row);
        response.setContentType("text/csv");
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\";");
catch(Exception e) {
        //Exception block
}
finally {
        try {
            csvWriter.flush();
        } catch (IOException e) {
            logger.error("Exception while flushing file writer and CSV writer",e);
        }

    }

But it showing csv on browser, rather than asking me save as option for download.

What is wrong in the code or is there any other way to do the same?

  • Two screws: lie and let the filename end on .xls, and Content-Type may be "application/vnd.ms-excel" – Joop Eggen Jul 04 '16 at 11:33
  • @JoopEggen it did not worked, still opening on browser – Rohit Sharma Jul 04 '16 at 11:51
  • Content-Type `application/bin` is used often for pure downloads, should do, because that the browser cannot open. – Joop Eggen Jul 04 '16 at 11:54
  • Oooh, first set the headers, then write! Sorry did not see that. But application/bin still holds. The header lines are outputted before an empty line and then the content, Buffering of small output often makes the order irrelevant, but the order should be kept on principle. – Joop Eggen Jul 04 '16 at 11:56
  • Thanks @JoopEggen , issue was with headers only. Setting header first worked – Rohit Sharma Jul 04 '16 at 12:35

1 Answers1

0

You can refer below code. This will ask you for 'Save' popup.

set your data in request attribute as ArrayList like request.setAttribute("list", list) and send it to JSP file.

Write this code in your JSP file.

<%
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition","attachment; filename=Report_File_Name.xls");
    response.setHeader("CookiesConfigureNoCache", "false");             
    response.setHeader("Pragma","private,no-cache");     
    response.setHeader("Cache-control","private,no-store,no-cache,max-age=0,must-revalidate");

    ArrayList<String> List = (ArrayList<String>) request.getAttribute("list");
        for(int i = 0; i < List.size(); i++){
    %>
            <%=List.get(i).toString()%><br>
    <%
        }

    %>
Bhushan
  • 287
  • 3
  • 6
  • 16