在 Java servlet 中创建和下载 CSV 文件 [英] Create and download CSV file in a Java servlet

查看:42
本文介绍了在 Java servlet 中创建和下载 CSV 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Java ExtJS 应用程序,我需要在其中创建和下载 CSV 文件.

I am working on Java ExtJS application in which I need to create and download a CSV file.

  • 单击按钮时,我希望将 CSV 文件下载到客户的机器.
  • 在按钮侦听器上,我正在使用 AJAX 调用 servlet.我在那里正在创建 CSV 文件.

我不想将 CSV 文件保存在服务器中.我希望应该使用下载选项动态创建该文件.我希望将文件的内容创建为字符串,然后将内容作为 file 提供,它将在浏览器中以下载模式打开(这是我用其他语言实现的,但不是确定如何在 Java 中实现它).

I don't want the CSV file to be saved in the server. I want the file should be created dynamically with a download option. I want the contents of a file to be created as a string and then I will serve the content as file in which it will open as download mode in browser (this I have achieved in other language, but not sure how to achieve it in Java).

这是我的代码,仅用于创建 CSV 文件,但如果我只能将文件下载为 CSV,我真的不想创建或保存 CSV 文件.

Here is my code only to create a CSV file, but I really don't want to create or save CSV file if I can only download the file as CSV.

public String createCSV() {
    try {
        String filename = "c:\test.csv";
        FileWriter fw = new FileWriter(filename);
        fw.append("XXXX");
        fw.append(',');
        fw.append("YYYY");
        fw.append(',');
        fw.append("ZZZZ");
        fw.append(',');
        fw.append("AAAA");
        fw.append(',');
        fw.append("BBBB");
        fw.append('
');

        CSVResult.close();

        return "Csv file Successfully created";
    } catch(Exception e) {
        return e.toString();
    }
}

谁能帮我解决这个问题.

Can any one help me on this.

谢谢

推荐答案

我得到了解决方案,并在下面发布.

I got the solution and I am posting it below.

public void doGet(HttpServletRequest request, HttpServletResponse response)
{
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename="userDirectory.csv"");
    try
    {
        OutputStream outputStream = response.getOutputStream();
        String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg
";
        outputStream.write(outputResult.getBytes());
        outputStream.flush();
        outputStream.close();
    }
    catch(Exception e)
    {
        System.out.println(e.toString());
    }
}

这里我们不需要在服务器中保存/存储文件.

Here we don't need to save / store the file in the server.

谢谢

这篇关于在 Java servlet 中创建和下载 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆