Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

Tuesday, July 29, 2014

Excel Generator in Java using POI and Reflection

Excel Generator in JAVA using apache POI and Reflection


Code Snippet:


    @SuppressWarnings("unchecked")
    public HSSFWorkbook exportToCSV(Object srcDtos, String[] columnList,
            String[] valueIdList, String title
) {
       
        try {
           
            List<Object> dtoList = null;
            HSSFRow reportRow = null;
            int rowNum = 1;
            int colIndex = 0;
            String reportRowValue = "";
           
            if (srcDtos == null){
                return null;
            } else {
                dtoList = (ArrayList<Object>)srcDtos;
            }
           
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(title);
                       
            /**
             * setting up the report header
             */
            HSSFRow reportHeader = sheet.createRow(0);

            for (String column : columnList) {
                reportHeader.createCell(colIndex++).setCellValue(column);
            }

            Method invokeMethod = null;
            Class<?> reqClass = null;
            // Loading methods parameters
            Class[] parameter = new Class[1];
            String getColumn = "";
            try { 
               
                for (Object srcClassObj : dtoList) {

                    /**
                     * creating the report row content
                     */
                    reportRow = sheet.createRow(rowNum++);
                    reportRowValue = "";
                    int rowColIndex = 0;
                   
                    Class dtoClzName =srcClassObj.getClass();
                   
                    reqClass = Class.forName(dtoClzName.getName());
               

                    for (String columnField : valueIdList) {
                         
                        getColumn = "get" + initCapString(columnField);

                        parameter[0] = String.class;

                        invokeMethod = reqClass.getMethod(getColumn);

                        Object tmpObj = invokeMethod.invoke(srcClassObj);

                        reportRowValue = (tmpObj == null ? "" : tmpObj
                                .toString());

                        reportRow.createCell(rowColIndex++).setCellValue(reportRowValue);

                    }

                }

            } catch (ClassNotFoundException e) {
                logger.error("Error during the CSV generation --->" +
                        e.getMessage());
            }
           
            return workbook;

        } catch (Exception e) {
            logger.error("Error during the CSV generation --->"
                    +   e.getMessage());
        }
        return null;
    }



    /**
     * method to init capitalize the given string(first letter as CAPITAL)
     * @param srcString
     * @return
     */
    public static String initCapString(String srcString) {
        String[] arr = srcString.split(" ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                    .append(arr[i].substring(1)).append(" ");
        }
        return sb.toString().trim();
    }



public class VelsErrorMsgDTO implements Serializable {

    private Long errorMsgID;
    private String institutionID;
    private String errorMsgTitle;
    private String errorMsgDescription;
    private String lastUpdtTime;

    public Long getErrorMsgID() {
        return errorMsgID;
    }


    public void setErrorMsgID(Long errorMsgID) {
        this.errorMsgID = errorMsgID;
    }


    public String getInstitutionID() {
        return institutionID;
    }


    public void setInstitutionID(String institutionID) {
        this.institutionID = institutionID;
    }


    public String getErrorMsgTitle() {
        return errorMsgTitle;
    }


    public void setErrorMsgTitle(String errorMsgTitle) {
        this.errorMsgTitle = errorMsgTitle;
    }


    public String getErrorMsgDescription() {
        return errorMsgDescription;
    }


    public void setErrorMsgDescription(String errorMsgDescription) {
        this.errorMsgDescription = errorMsgDescription;
    }


    public String getLastUpdtTime() {
        return lastUpdtTime;
    }


    public void setLastUpdtTime(String lastUpdtTime) {
        this.lastUpdtTime = lastUpdtTime;
    }
   
}


Here the arguements

srcDtos      ------> actual  java DTO objects which carries your data
columnList  ------> Column header list
valueIdList  ------> java property names need to be invoked from DTO object(getter method of the
                                given  java field(example userName , address ..) would be  invoked to get the actual
                                value  that need to be displayed in excel file)
 title ---------------> Report title




    public static void main(String[] args) {
        List<VelsErrorMsgDTO > dtoList = new ArrayList<VelsErrorMsgDTO >();
        VelsErrorMsgDTO dto = new VelsErrorMsgDTO ();
        dto.setErrorMsgID(1L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("101");
        dtoList.add(dto);
       
        dto = new CIErrorMsgDTO();
        dto.setErrorMsgID(2L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("608");
        dtoList.add(dto);
       
        String[] columnList={ "Error Msg","Description","Institution"};
        String[] valueIdList={ "errorMsgTitle","errorMsgDescription","institutionID"};
        try {
          
            FileOutputStream fileOut = new FileOutputStream("C:\\temp\\TestXcel1.xls");
            workbook.write(fileOut);
            fileOut.close();

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