Tuesday, September 20, 2016

ADF : Export to Excel Programmatically using fileDownloadActionListener tag

Another way exporting table results into excel is by using fileDownloadActionListener on button action 

Drop fileDownloadActionListener  tag on button , set content type to application/vnd.ms-excel and bind it to bean method.




In Bean code get desired rows append attribute value with '\t' for next cell and '\n' next line for next row in excel

private static final String LINEBREAK = "\n";
private static final String NEXTCELL = "\t";

public void exportToExcel(FacesContext facesContext, OutputStream outputStream) throws IOException {
    DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding binding = dc.findIteratorBinding("EmployeesVO1Iterator");
    ViewObject vo = binding.getViewObject();
    StringBuilder sb = new StringBuilder();
    sb.append("First Name").append(NEXTCELL).append("last Name").append(NEXTCELL).append("Email").append(LINEBREAK);
    vo.setCurrentRow(vo.first());
    Row current = vo.getCurrentRow();
    while (current != null) {
        String firstName = (String)current.getAttribute("FirstName");
        String lastName = (String)current.getAttribute("LastName");
        String email = (String)current.getAttribute("Email");
        sb.append(firstName).append(NEXTCELL).append(lastName).append(NEXTCELL).append(email).append(NEXTCELL).append(LINEBREAK);
        current = vo.next();
    }
    outputStream.write(sb.toString().getBytes());
    outputStream.flush();
}

Output
Employees table will show only 3 rows

Click on export results button will export data into excel ,below is result




Happy Learning !!

No comments:

Post a Comment