Writing out from a Java Server Faces table to a CSV….

Imagine if you will that you have a Java Server Faces table and you want to write it out to a CSV file.

1. Put The following code in your application bean.

public String OutputFromTableToCSV(
String sFilename,
TableRowGroup tableRowGroup1,
CachedRowSetDataProvider tblzonesDataProvider) {
// Create an ooutput text file
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try {
out = new FileOutputStream(sFilename
+".txt");

p=new PrintStream(out);
} catch (Exception e) {
return "Error, could not write to "+sFilename+".txt";
}

String sFields = "";
String sColumnTitle = "";
String sThisFieldName="";
List theseColumns = tableRowGroup1.getChildren();
// Columns
for (int i = 0; i < tableRowGroup1.getColumnCount(); ++i) {
sColumnTitle = sColumnTitle.concat(sColumnTitle);
sColumnTitle = sColumnTitle.concat(",");

// Get the SQL mapped fields
TableColumn thisComponant = (TableColumn) theseColumns.get(i);
try {
sColumnTitle = sColumnTitle.concat(
thisComponant.getHeaderText());
} catch (Exception e) {
}
}
if (!sColumnTitle.equals("")) {
sColumnTitle=sColumnTitle.substring(1); // Chop off initial ,
}
// Write it out
p.println(sColumnTitle);

RowKey[] TheseRows = tblzonesDataProvider.getAllRows();
for (int rowCount = 0; rowCount < TheseRows.length; ++rowCount) {
// Now do the rows
tblzonesDataProvider.setCursorRow(TheseRows[rowCount]);
for (int i = 0; i < tableRowGroup1.getColumnCount(); ++i) {
sFields = sFields.concat(sFields);
sFields = sFields.concat(",");
// Get the SQL mapped fields
TableColumn thisColumn = (TableColumn) theseColumns.get(i);
UIComponent thisChild=(UIComponent) thisColumn.getChildren().get(0);
// ",[#{currentRow.value['ZoneDescription']}]"
try {
sThisFieldName = thisChild.getValueExpression("text").toString();
sThisFieldName = sThisFieldName.substring(
sThisFieldName.indexOf("['") + 2);
sThisFieldName = sThisFieldName.substring(0,
sThisFieldName.indexOf("']"));

} catch (Exception e) {
}

// Add the field to the string to write out

sFields = sFields.concat(
tblzonesDataProvider.getValue(sThisFieldName).toString()
);

}
if (!sFields.equals("")) {
sFields = sFields.substring(1); // Chop off initial ,
}
p.println(sFields);

sFields="";
} // Next Row
// At this point we have to csv strings
// sfields and column title

// Now we have a comma delimited string called sresult in theory

p.close();
return "OK";
}

2. On the form with the JSF page.
a. Add the binding attribute to the tableRowGroup (in the left hand bottom pane).

Create an “Export to CSV file” button and in the event when clicked add this code:-

thefilename - the filename you want to write to
tableRowGroup1 - The table row group from your JSF page table
yourdataprovider - The data provider that feeds the JSF table

getApplicationBean1().OutputFromTableToCSV("thefilename", tableRowGroup1, yourDataProvider);

Leave a Reply