创建和下载CSV文件Java(Servlet) [英] Create and Download CSV file Java(Servlet)

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

问题描述

我正在开发JAVA EXTJS应用程序,我需要在其中创建和下载CSV文件。

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

点击按钮我希望下载CSV文件客户机器。

On clicking a button I want a CSV file to be downloaded in clients machine.

在按钮监听器上我使用ajax调用servlet。我在那里创建一个CSV文件。

On buttons listener I am calling a servlet using ajax. There I am creating a CSV file.

我不希望CSV文件保存在服务器中。我希望该文件应该通过下载选项动态创建。

I don't want the CSV file to be saved in the server. I want the file should be created dynamically with download option.

我希望文件的内容创建为字符串然后我将内容作为文件提供给它将在浏览器中以下载模式打开。(这是我用其他语言实现的,但不知道如何在java中实现它)

I want the contents of a file is created as 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 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();
    }
}

任何人都可以帮我解决这个问题。

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\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.

谢谢

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

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