如何使用servlet创建CSV文件? [英] How to create a CSV file using servlet?

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

问题描述

我想从 servlet 下载CSV文件.我的对象数组(object[])中有数据,我需要将其写入CSV并下载.

I want to download a CSV file from a servlet. I have data in the array of objects (object[]), I need to write it into CSV and download.

您能帮助我如何在servlet类中做到这一点吗?

Could you help me how to do this in a servlet class?

推荐答案

Object[]如何表示CSV数据?它包含一行包含几列还是几行包含一列?我想Object[][]List<List<Object>>更有意义.

How can Object[] ever represent CSV data? Does it contain one row with several columns or several rows with one column? I'd imagine that Object[][] or List<List<Object>> makes more sense.

无论如何,创建CSV文件时,您必须遵守 RFC4180规范.基本上很简单,只有3个严格的规则:

Anyway, when creating a CSV file you've to adhere the RFC4180 spec. It's basically simple, there are only 3 strict rules:

  1. 字段之间用逗号分隔.
  2. 如果在字段中出现逗号,则该字段必须用双引号引起来.
  3. 如果字段中出现双引号,则该字段必须用双引号引起来,并且该字段中的双引号必须用另一个双引号转义.

这是一个启动示例,该示例完全基于List<List<T>>作为源,而OutputStream作为目的地.

Here's a kickoff example which does exactly that based on a List<List<T>> as source and an OutputStream as destination.

public static <T> void writeCsv (List<List<T>> csv, char separator, OutputStream output) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
    for (List<T> row : csv) {
        for (Iterator<T> iter = row.iterator(); iter.hasNext();) {
            String field = String.valueOf(iter.next()).replace("\"", "\"\"");
            if (field.indexOf(separator) > -1 || field.indexOf('"') > -1) {
                field = '"' + field + '"';
            }
            writer.append(field);
            if (iter.hasNext()) {
                writer.append(separator);
            }
        }
        writer.newLine();
    }
    writer.flush();
}

这是在Servlet中使用它的方式:

Here's how you can use it in a Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<List<Object>> csv = getItSomehow();
    response.setHeader("Content-Type", "text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=\"file.csv\"");
    writeCsv(csv, ';', response.getOutputStream());
}

(请注意,欧洲地区的CSV文件使用分号而不是逗号,可以随时更改)

attachmentContent-Disposition将强制执行另存为对话框.请注意,MSIE的行为是,在另存为对话框中,它没有将filename作为默认文件名,而是使用了pathinfo的最后一部分.因此,例如,如果 http://example.com/csv 调用了此servlet,那么您将获得csv作为默认文件名.而是将其附加到pathinfo,如下所示 http://example.com/csv/file.csv . servlet仅应映射在/csv/*url-pattern上,而不是/csv.

The Content-Disposition of attachment will force a Save As dialogue. Note that MSIE has the misbehaviour that it doesn't take the filename as default filename in the Save As dialogue, but it instead takes the last part of the pathinfo. So if this servlet is for example invoked by http://example.com/csv, then you'll get csv as default filename. Rather append it to the pathinfo like follows http://example.com/csv/file.csv. The servlet should only be mapped on an url-pattern of /csv/* instead of /csv.

这篇关于如何使用servlet创建CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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