简体   繁体   English

在 Java servlet 中创建和下载 CSV 文件

[英]Create and download CSV file in a Java servlet

I am working on Java ExtJS application in which I need to create and download a CSV file.我正在开发 Java ExtJS 应用程序,我需要在其中创建和下载 CSV 文件。

  • On clicking a button I want a CSV file to be downloaded to a client's machine.单击按钮时,我希望将 CSV 文件下载到客户端的机器上。
  • On buttons listener I am calling a servlet using AJAX.在按钮侦听器上,我使用 AJAX 调用 servlet。 There I am creating a CSV file.在那里我正在创建一个 CSV 文件。

I don't want the CSV file to be saved in the server.我不希望将 CSV 文件保存在服务器中。 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).我希望将文件的内容创建为字符串,然后将内容作为文件提供,它将在浏览器中以下载模式打开(这是我用其他语言实现的,但不确定如何在 Java 中实现它)。

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.这是我仅用于创建 CSV 文件的代码,但如果我只能将文件下载为 CSV,我真的不想创建或保存 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.谁可以帮我这个事。

Thanks谢谢

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.这里我们不需要在服务器中保存/存储文件。

Thanks谢谢

First of all you need to get the HttpServletResponse object so that you can stream a file into it.首先,您需要获取 HttpServletResponse 对象,以便您可以将文件流式传输到其中。

Note : This example is something I Wrote for one of my projects and it works.Works on Java 7.注意:这个例子是我为我的一个项目写的,它在 Java 7 上有效。

Assuming you got the HttpServletResponse you can do something like this to stream a file.假设你有 HttpServletResponse 你可以做这样的事情来流式传输文件。 This way the file will be saved into clients' machine.这样文件将被保存到客户的机器中。

public void downloadFile(HttpServletResponse response){ 

        String sourceFile = "c:\\source.csv";
        try {
            FileInputStream inputStream = new FileInputStream(sourceFile);
            String disposition = "attachment; fileName=outputfile.csv";
            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", disposition);
            response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));

        } catch (IOException e) {
            logger.error("Error occurred while downloading file {}",e);
        }
}

And the stream method should be like this.而流方法应该是这样的。

private long stream(InputStream input, OutputStream output) throws IOException {

    try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
        ByteBuffer buffer = ByteBuffer.allocate(10240);
        long size = 0;

        while (inputChannel.read(buffer) != -1) {
            buffer.flip();
            size += outputChannel.write(buffer);
            buffer.clear();
        }
        return size;
    }
}

What this does is, get an inputstream from your source file and write that stream into the outputstream of the HttpServletResponse.它的作用是从源文件中获取输入流并将该流写入 HttpServletResponse 的输出流。 This should work since it works perfectly for me.这应该有效,因为它对我来说非常有效。 Hope this helps.希望这可以帮助。 Sorry for my bad English.对不起,我的英语不好。

I would like add something to the answer by gaurav.我想在 gaurav 的答案中添加一些内容。 I recently had to implment this functionality in a project of mine and using javascript was out of the question becuase we had to support IE 9. What is the problem with IE 9?我最近不得不在我的一个项目中实现这个功能,使用 javascript 是不可能的,因为我们必须支持 IE 9。IE 9 有什么问题? ( Export to CSV using jQuery and html ), see the second answer in the link. 使用 jQuery 和 html 导出到 CSV ),请参阅链接中的第二个答案。

I needed an easy way to convert a ResultSet of a database query to a string which represent the the same data in CSV format.我需要一种简单的方法将数据库查询的 ResultSet 转换为以 CSV 格式表示相同数据的字符串。 For that I used http://opencsv.sourceforge.net/ which provided an easy way to get a String ot of the ResultSet, and the rest is as above answer did it.为此,我使用了http://opencsv.sourceforge.net/ ,它提供了一种简单的方法来获取 ResultSet 的 String ot,其余的就像上面的答案一样。

THe examples in the project soruce folder give good examples.项目源文件夹中的示例给出了很好的示例。

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

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