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

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

问题描述

我想从下载csv文件来自 Object [] obj = search.getSearch();



我有数据 object [] ,我需要写入csv并下载。 >

您能帮助我在servlet类中做些什么吗?

解决方案

Object [] 曾经代表CSV数据吗?它包含一行有多列还是几行有一列?我想象 Object [] [] List< List< Object>> / p>

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


  1. 字段用逗号分隔。

  2. 如果在字段中出现逗号,则该字段必须用双引号括起来。

  3. 如果在字段中出现双引号,则该字段必须用双引号

这里是一个启动示例,它完全基于一个列表< List< T>> 作为来源,并将 OutputStream 作为目标。

  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中使用它的方法:

  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文件,随时可以更改)



Content-Disposition >附件将强制另存为对话框。注意,MSIE的不正确之处在于它不会将 filename 作为另存为对话框中的默认文件名,的pathinfo。因此,如果此servlet例如由 http://example.com/csv 调用,那么您将获得 csv 作为默认文件名。而是将其附加到pathinfo,如下所示: http://example.com/csv/file.csv 。 servlet只应映射到 / csv / * url-pattern 上,而不是 / csv


I want to download csv file from servlet.Data comes from Object[] obj=search.getSearch();

I have data the object[], i need to write into csv and download.

Could you help me how to do in servlet class?

解决方案

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.

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

  1. Fields are separated by a comma.
  2. If a comma occurs within a field, then the field has to be surrounded by double quotes.
  3. If a double quote occurs within a field, then the field has to be surrounded by double quotes and the double quote within the field has to be escaped by another double quote.

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();
}

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());
}

(note that Europe based locales use a semicolon instead of comma for CSV files, feel free to change)

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天全站免登陆