Generate Excel file in Oracle ADF using Apache POI

Requirement:Generate excel file using open source “Apache POI” to generate excel spreadsheets from my ADF application.

Advantage of using POI over default export collectionListener of ADF –

1. Using Apache POI, you can not only export excels but also can read excel files (.xls or .xlsx) from local machines and upload them to ADF applications
2. User has more control on the excel output file (than using “Export Collection Action Listener”)
for e.g. you can put data formatting for your currency/date column, freeze panes, apply filters etc.
3. Size of generated excel is less than from export CollectionListener.

Solution-

You need to download the apache POI jar from poi.apache.org

–>> poi-3.7-20101029.jar
You need to add this jar in project libraries and classpath of project.

Creating a sample project (using Department and Employee tables) and attaching libararies.

I would like to keep it simple as we don’t want to focus on any steps other than excel here, here are quick steps to create a sample application

1. create view object using query on locations table.
2. Expose the VO to applicationModule.then drag drop VO from data control to page as table
3. Place a command button anywhere on the page and label it as “ExporToExcel”
4. Drop a “” component on this button.
Put property of af:fileDownloadActionListener as follows
-> contentType: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or you can use “application/octet-stream” .
-> ExcelFromPoi.xls
-> Method: #{PoiBean.generateExcel} //custom method call to export data

Now writing a custom method in managed bean to export locations shown in the screen.
I am writing an generateExcel() method.

In short, follow the steps-
create a Workbook object.create a Sheet object.Get object of bindings .After that we will get page iterator and from that iterator we will get all rows in that range. Start creating row first and then cells. After completion of sheet , we will writing outputStream on the workBook.

Following is code of managed bean –

package vinay.view;

import com.sun.jmx.snmp.Timestamp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import oracle.adf.model.BindingContainer;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;

import oracle.adf.model.binding.DCIteratorBinding;



public class PoiBean {
    public PoiBean() {
    }


        public static BindingContainer getBindingContainer() {
            //return (BindingContainer)JSFUtils.resolveExpression("#{bindings}");
            return (BindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        }

        public static DCBindingContainer getDCBindingContainer() {
            return (DCBindingContainer)getBindingContainer();
        }
      
      public void generateExcel(FacesContext facesContext, OutputStream outputStream) throws IOException {
          try {
         
                            
                                HSSFWorkbook workbook = new HSSFWorkbook();
                                    HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
              
                                DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
                                DCIteratorBinding dcIteratorBindings = bindings.findIteratorBinding("ViewObj1Iterator");
                                HSSFRow  excelrow = null;
              
                                        // Get all the rows of a iterator
                                        oracle.jbo.Row[] rows = dcIteratorBindings.getAllRowsInRange();
                                    int i = 0;
                             

                                            for (oracle.jbo.Row row : rows) {

                                                //print header on first row in excel
                                                if (i == 0) {
                                                    excelrow = (HSSFRow)worksheet.createRow((short)i);
                                                    short j = 0;
                                                    for (String colName : row.getAttributeNames()) {
                                                      
                                                            HSSFCell cellA1 = excelrow.createCell((short) j);
                                                            cellA1.setCellValue(colName);
                                                            j++;
                                                        
                                                    }
                                                }

                                                //print data from second row in excel
                                                ++i;
                                                short j = 0;
                                                excelrow = worksheet.createRow((short)i);
                                                for (String colName : row.getAttributeNames()) {
                                                    System.out.println("hello "+row.getAttribute(colName));
                                                    System.out.println("hello "+colName);
                                                        HSSFCell  cell = excelrow.createCell(j);
                                                    if (colName.equalsIgnoreCase("DepartmentId")) {

                                                       
                                                        cell.setCellValue(row.getAttribute(colName).toString());
                                                        System.out.println("colName "+colName+"row.getAttribute(colName).toString()"+row.getAttribute(colName).toString());
                                                    }
                                                        //logic for cell formatting
                                                        if (colName.equalsIgnoreCase("DepartmenName")) {
                                                            cell.setCellValue(row.getAttribute(colName).toString());
                                                            
                                                        }
                                                        //make it double if you want and convert accordingly
                                                        else if (colName.equalsIgnoreCase("LocationId")){
                                                            cell.setCellValue(row.getAttribute(colName).toString());
                                                        }
                                                        else if (colName.equalsIgnoreCase("ManagerId")){
                                                            if(null!=row.getAttribute(colName)){
                                                            cell.setCellValue(row.getAttribute(colName).toString());
                                                            }
                                                        } else
                                                         cell.setCellValue(row.getAttribute(colName).toString());

                                                        j++;
                                                      
                                                    }
                                                
                                                   worksheet.createFreezePane(0, 1, 0, 1);
                                               } 
              workbook.write(outputStream);
              outputStream.flush();
              
          }
                                            catch (Exception e) {
                                          e.printStackTrace();
                                            }
                                        
      }
      }

You can freeze the header like this —

worksheet.createFreezePane(0, 1, 0, 1);

Resize the column automatically –

            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);
            sheet.autoSizeColumn(3);

And finally you can get the generated excel report like below

you can download the sample application from below, I have also illustrat how you can generate excel using export collectionListner in sample application.Button label as exportCollectionActionListener –

exportToExcel

Happy coding with Vinay kumar in Techartifact

Dynamic Creation of cascading Lov in oracle ADF or model driven Lov in Oracle ADF.

Requirement – I am working on tricky requirement where i have two child component and one child LOV.How to do that?

Solution- Well if you have working knowledge of cascading LOV in then we pass bind parameter of parent LOV attribute in child LOV View Accessor(VA) . But in this scenario , we have two master LOV. then we will be doing by passing through managed bean, using Application module session .

What i have done.I have used HR schema .

I have 3 view object. one as country table of HR schema.One View object for location table.One view which have all transient attribute and consider to be main view object.

As i found this approach in Jobinesh’s blog- i write a custom method in applicationModuleImpl.java as below –

    public void setLocationIDSessionData(String locId){
          System.out.println("hello 232323&&&"+locId);
        this.getSession().getUserData().put("LocationId", locId);
        
      }

I have getUserData method of applicationModule interface which returns a java.util.Hashtable which may be used to store user specific context that is related to this application session.

Read all other method related to this
http://docs.oracle.com/cd/E12839_01/apirefs.1111/e10653/oracle/jbo/ApplicationModuleHandle.html

Ok, coming back to this requirement – I used a managed bean in backing bean scope where i executed the binding of applicationModuleImpl custom method as below –

    public void executec(String valueChangeEvent) {
    BindingContext bctx = BindingContext.getCurrent();
           BindingContainer bindings = bctx.getCurrentBindingsEntry();
           OperationBinding op =
               (OperationBinding)bindings.getOperationBinding("setLocationIDSessionData");
           op.getParamsMap().put("locId",valueChangeEvent);
           op.execute();
    }

Here we are passing the value of both LOV to locationId to custom applicationModuleImpl method.In both parent LOV , i create valuechangeEvent method , which get the current selected countryId and pass to custom applicationModuleImpl method. that is below –

    public void VC(ValueChangeEvent valueChangeEvent) {
      System.out.println("hello &&&"+valueChangeEvent.getNewValue());
      
       
        executec(valueChangeEvent.getNewValue().toString());
    }

    public void vc2(ValueChangeEvent valueChangeEvent) {
        System.out.println("hello &&&34343"+valueChangeEvent.getNewValue());
        executec(valueChangeEvent.getNewValue().toString());
    }

Now we have final task, we have to set the value of child lov bind parameter in child View Accessor as adf.userSession.userData.LocationId

That’s it.now we will run the jspx , which have all 3 lov.2 parent and one child LOV.
for displaying LOV , we need to click on create button.after click you can see all 3 LOVs.

After selecting county as CH from countryLov1 , we will see different values in location ID.

Now we will select country as IN from countryLov2 , we will see different values in location ID.

You can download the sample application here.

ModelDrivernCascadingLOVs

Happy coding with Vinay kumar in techartifact….

ADF_FACES-30107: The view state of the page has expired. Load the page again.

Requirment- Resolving ADF_FACES-30107: The view state of the page has expired. Load the page again.
ugly error actually.- you don’t know what went wrong- and you will see a very long error message like
ADF_FACES-30107: The view state of the page has expired. Load the page again………………………………………………………………………..

What’s the problemFirst understand , why we get this error – The ViewExpiredException will be thrown whenever the javax.faces.STATE_SAVING_METHOD is set to server (default) and the enduser sends a HTTP POST request using or or some valueChangeEvent on a view, while the associated view state isn’t available in the session anymore. The view state is identified by a hidden input field javax.faces.ViewState of the

. With the state saving method set to server, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate() in server), then the serialized view state is not available anymore in the session and the enduser will get this exception.With the state saving method set to client, the javax.faces.ViewState hidden input field contains instead the whole serialized view state, so the enduser won’t get a ViewExpiredException when the session expires.

In the oracle documentation this error states-

ADF_FACES-30107: The view state of the page has expired. Reload the page.
Cause: The UI state of the view has expired, either because the back button has been used too many times, too many page submissions have occurred on ther pages, or because of an underlying bug in the view code.
Action: The application using ADF should install an ADFc error handler for JSF ViewExpiredExceptions, or configure the org.apache.myfaces.trinidad.CLIENT_STATE_MAX_TOKENS web.xml parameter to a larger value.
Level: 2

Type: ERROR

Impact: Logging

How to resolve this – Find for the org.apache.myfaces.trinidad.CLIENT_STATE_MAX_TOKENS in web.xml as context parameter . If it not set as it happened to my application. Set this parameter and put value.Sometimes,it will not work for value for 15 to 20. I set it as 500.This mean , it can handle this much page submission for the pages.

Great.After reading this ,you resolved the error.

Happy coding with Vinay kumar in techartifact……