我正在使用<ui:repeat>
来显示列表。现在我想将整个列表导出到CSV文件。在JSF 2.0中有没有办法做到这一点?
答案 0 :(得分:2)
是的,有办法。添加一个命令按钮,显示“export”。
<h:form>
<h:commandButton value="export" action="#{bean.export}" />
</h:form>
然后,在export()
方法中,迭代List<Something>
中显示的<ui:repeat>
,并以有效的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;
}