简体   繁体   English

生成/下载CSV文件而不存储在服务器上

[英]Generate/download CSV file without storing on server

I'm using the apache.commons.csv library in Java to generate CSV and make it downloadable without storing on server using following code: 我正在使用Java中的apache.commons.csv库生成CSV并使其可下载,而无需使用以下代码存储在服务器上:

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. 但是它在浏览器上显示的是csv,而不是要求我另存为下载选项。

What is wrong in the code or is there any other way to do the same? 代码有什么问题,或者有其他方法可以做到这一点?

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. 将请求属性中的数据设置为ArrayList,例如request.setAttribute("list", list)并将其发送到JSP文件。

Write this code in your JSP file. 将此代码写入您的JSP文件。

<%
    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>
    <%
        }

    %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM