【问题标题】:Export ui:repeat list as CSV file将 ui:repeat 列表导出为 CSV 文件
【发布时间】:2012-04-03 20:06:04
【问题描述】:

我正在使用<ui:repeat> 来显示列表。现在我想将整个列表导出到 CSV 文件。在 JSF 2.0 中有没有办法做到这一点?

【问题讨论】:

    标签: jsf-2 export-to-csv


    【解决方案1】:

    是的,有办法。添加一个显示“导出”的命令按钮。

    <h:form>
        <h:commandButton value="export" action="#{bean.export}" />
    </h:form>
    

    然后,在export() 方法中,遍历您在&lt;ui:repeat&gt; 中显示的List&lt;Something&gt;,并以有效的CSV 格式打印每一行/列。 CSV格式规则很简单,只有3条:

    • 字段用逗号分隔。
    • 如果逗号出现在字段中,则该字段必须用双引号括起来。
    • 如果字段中出现双引号,则该字段必须用双引号括起来,并且该字段中的双引号必须用另一个双引号转义。

    所以它看起来像这样:

    public void export() throws IOException {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        String filename = "somename.csv";
    
        ec.responseReset();
        ec.setResponseContentType("text/csv");
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        Writer writer = ec.getResponseOutputWriter();
    
        for (Something something : somethings) { // somethings is your List<Something>
            writer.append(toCsvField(something.getFoo()))
                  .append(',')
                  .append(toCsvField(something.getBar()))
                  .append(',');
                  .append(toCsvField(something.getBaz()))
                  .append('\n');
        }       
    
        fc.responseComplete(); // Important! Otherwise JSF will perform navigation.
    }
    
    public static String toCsvField(Object value) {
        if (value == null) {
            return "";
        }
    
        String field = String.valueOf(value).replace("\"", "\"\"");
    
        if (field.indexOf(',') > -1 || field.indexOf('"') > -1) {
            field = '"' + field + '"';
        }
    
        return field;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2013-06-09
      • 1970-01-01
      相关资源
      最近更新 更多