Friday, February 12, 2016

Export Table data or VOIterator Data in Excel in ADF using fileDownloadActionListener

Using fileDownloadActionListener we can export data as follows in adf:

Steps:

1) Create Adf Application
2)Create EO and VO for Employee Table.
3)Create page and Drag and Drop Employee VO DataControl in page.
4)Take one button named as "Export Data"
5)In Component Palette search fileDownloadActionListener and Drag and Drop on Export Data button

6)In properties of fileDownloadActionListener set following values to attributes:

 contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
filename="Employee.xls"
method="#{Employees.getExcel}"

create method in Employee bean.

and paste following code in method getExcel()

NOTE :  First add library poi-3.7-20101029 .jar

    public void getExcel(FacesContext facesContext, OutputStream outputStream) {

        DCIteratorBinding dcIteratorBindings = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet worksheet = workbook.createSheet("Employee"); //Tab Name

            DCBindingContainer bindings = (DCBindingContainer) BindingContext.getCurrent().getCurrentBindingsEntry();
            dcIteratorBindings = bindings.findIteratorBinding("EmployeesView1Iterator"); // VOIterator
            HSSFRow excelrow = null;

            // Get all the rows of a iterator
            Row[] rows = dcIteratorBindings.getAllRowsInRange();

            int i = 0;
            for (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()) {

                    HSSFCell cell = excelrow.createCell(j);
                    if (row.getAttribute(colName) != null) {
                        cell.setCellValue(row.getAttribute(colName).toString());
                    }
                    j++;
                }
                worksheet.createFreezePane(0, 1, 0, 1);
            }
            workbook.write(outputStream);
            outputStream.flush();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

7)run the project


Hope it will help you

No comments:

Post a Comment