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

查看:97
本文介绍了在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文件.
  • On clicking a button I want a CSV file to be downloaded to a client's machine.
  • On buttons listener I am calling a servlet using AJAX. There I am creating a CSV file.

我不希望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('\n');

        CSVResult.close();

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

有人可以帮我吗?

谢谢

推荐答案

我找到了解决方案,并将其发布在下面.

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\n";
        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天全站免登陆