smartGwt导出CSV的方法
已经测试过,下面的方法可以正常使用。只需放入smartgwt环境下即可
public void onModuleLoad() {
final ListGrid listGrid = new ListGrid();
listGrid.setFields(new ListGridField("Col1"), new ListGridField("Col2"), new ListGridField("Col3"));
Record[] data = new Record[5];
int counter = 0;
for (int i = 0; i < data.length; i++) {
data[i] = new ListGridRecord();
data[i].setAttribute("Col1", counter++);
data[i].setAttribute("Col2", counter++);
data[i].setAttribute("Col3", counter++);
}
listGrid.setData(data);
IButton button = new IButton("Export CSV");
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
StringBuilder exportedCSV = exportCSV(listGrid);
System.out.println(exportedCSV);// 打印到控制台
}
});
VLayout layout = new VLayout();
layout.addMember(button);
layout.addMember(listGrid);
layout.draw();
}
/**
* Export data from a listrgrid
* @param listGrid the {@link ListGrid}
* @return a {@link StringBuilder} containing data in CSV format
*/
private StringBuilder exportCSV(ListGrid listGrid) {
StringBuilder stringBuilder = new StringBuilder(); // csv data in here
// column names
ListGridField[] fields = listGrid.getFields();
for (int i = 0; i < fields.length; i++) {
ListGridField listGridField = fields[i];
stringBuilder.append(""");
stringBuilder.append(listGridField.getName());
stringBuilder.append("",");
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1); // remove last ","
stringBuilder.append("\n");
// column data
ListGridRecord[] records = listGrid.getRecords();
for (int i = 0; i < records.length; i++) {
ListGridRecord listGridRecord = records[i];
ListGridField[] listGridFields = listGrid.getFields();
for (int j = 0; j < listGridFields.length; j++) {
ListGridField listGridField = listGridFields[j];
stringBuilder.append(""");
stringBuilder.append(listGridRecord.getAttribute(listGridField.getName()));
stringBuilder.append("",");
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1); // remove last ","
stringBuilder.append("\n");
}
return stringBuilder;
}
打印到控制台的结果:
"Col1","Col2","Col3"
"0","1","2"
"3","4","5"
"6","7","8"
"9","10","11"
"12","13","14" 1 楼 showtime520 2011-07-29 这已经测试过,可以正常使用个毛啊,你就是从smartgwt论坛上复制粘贴下,你确定你认真看过这段代码?
这样做有什么意义