Search This Blog

Monday, September 10, 2012

Export To Excel in ADF

ADF 11g has provided the feature of exporting to excel using export listener as follows

<af:exportCollectionActionListener exportedId="tableId" type="excelHTML" title="My Excel Document" filename="testFile.xls"/>

This feature has couple of limitation

1. Export can be based on a single table. If multiple tables are given we get the following error.
Exported collection with the ID of: t1 t2 was not found. with t1, t2 being table Ids.

2. The current feature doesn't allow to export data based on page iterators. As there are many scenarios we base our export to excel on different data(iterators) in the real world.   A traditional approach of exporting data has addressed the above two problems. Below is the code...

public String exporttoexcel_action() throws IOException {
         String filename = "testFile.xls";
         FacesContext fc = FacesContext.getCurrentInstance();
         BindingContainer bc = BindingContext.getCurrent().getCurrentBindingsEntry();
         // get response object.
         HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
         // Set the file name
         response.setHeader("Content-disposition", "attachment; filename=" + filename);
         // Set MIME type to excel
         response.setContentType("application/vnd.ms-excel");
         PrintWriter out = response.getWriter();

         DCIteratorBinding theateriter = (DCIteratorBinding)bc.get("MyVO1Iterator");         
         printtoexcel(theateriter,out);

         out.println();

         DCIteratorBinding areaiter = (DCIteratorBinding)bc.get("MyVO2Iterator");
         printtoexcel(theateriter,out);
         out.close();

         fc.responseComplete();
         return null;
}



public void printtoexcel(DCIteratorBinding iter, PrintWriter out) {
         RowSetIterator rsi = iter.getRowSetIterator();
         String[] attNames = rsi.getRowAtRangeIndex(0).getAttributeNames();
         for (int i = 0; i < attNames.length-1; i++) {
         if (i > 0)
                out.print("\t"); // tab after each value
         out.print(attNames[i]);
}

Alternate Appraoches :

1. Using Apache open source POI APIs.
2. Other way to overcome this limitation is to override the export collection action listener class. (Never tried).

1 comment: