Example usage for org.apache.poi.ss.usermodel CellStyle setFont

List of usage examples for org.apache.poi.ss.usermodel CellStyle setFont

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel CellStyle setFont.

Prototype

void setFont(Font font);

Source Link

Document

set the font for this style

Usage

From source file:org.forzaframework.util.ExcelUtils.java

License:Apache License

public static CellStyle getDefaultHeaderCellStyle(Workbook wb, Boolean defaultFormat) {
    CellStyle headerCellStyle = null;
    if (defaultFormat != null && defaultFormat) {
        //Le damos formato a los encabezados
        headerCellStyle = wb.createCellStyle();
        headerCellStyle.setBorderBottom(BorderStyle.DOTTED);
        headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //        headerCellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //Creamos el tipo de fuente
        Font headerFont = wb.createFont();
        //            headerFont.setFontName(HSSFFont.FONT_ARIAL);
        headerFont.setBold(Boolean.TRUE);
        headerFont.setColor(Font.COLOR_NORMAL);
        headerFont.setFontHeightInPoints((short) 8);
        headerCellStyle.setFont(headerFont);
    }/*from   ww  w. j a  v  a 2s  .com*/
    return headerCellStyle;
}

From source file:org.generationcp.breeding.manager.crossingmanager.util.CrossingManagerExporter.java

License:Open Source License

private HashMap<String, CellStyle> createStyles(HSSFWorkbook wb) {
    HashMap<String, CellStyle> styles = new HashMap<String, CellStyle>();

    // set cell style for labels in the description sheet
    CellStyle labelStyle = wb.createCellStyle();
    labelStyle.setFillForegroundColor(IndexedColors.BROWN.getIndex());
    labelStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    Font labelFont = wb.createFont();
    labelFont.setColor(IndexedColors.WHITE.getIndex());
    labelFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    labelStyle.setFont(labelFont);
    styles.put(LABEL_STYLE, labelStyle);

    // set cell style for headings related to Conditions/Factors
    CellStyle factorHeadingStyle = wb.createCellStyle();
    factorHeadingStyle.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex());
    factorHeadingStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    factorHeadingStyle.setAlignment(CellStyle.ALIGN_CENTER);
    Font factorHeadingfont = wb.createFont();
    factorHeadingfont.setColor(IndexedColors.WHITE.getIndex());
    factorHeadingfont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    factorHeadingStyle.setFont(factorHeadingfont);
    styles.put(FACTOR_HEADING_STYLE, factorHeadingStyle);

    // set cell style for headings related to Constants/Variates
    CellStyle variateHeadingStyle = wb.createCellStyle();
    variateHeadingStyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
    variateHeadingStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    variateHeadingStyle.setAlignment(CellStyle.ALIGN_CENTER);
    Font variateHeadingFont = wb.createFont();
    variateHeadingFont.setColor(IndexedColors.WHITE.getIndex());
    variateHeadingFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    variateHeadingStyle.setFont(variateHeadingFont);
    styles.put(VARIATE_HEADING_STYLE, variateHeadingStyle);

    //set cell style for numeric values (left alignment)
    CellStyle numericStyle = wb.createCellStyle();
    numericStyle.setAlignment(CellStyle.ALIGN_LEFT);
    styles.put(NUMERIC_STYLE, numericStyle);

    return styles;
}

From source file:org.grible.excel.ExcelFile.java

License:Open Source License

public String saveToFile(Table table, String filePath) {
    try {/* w w  w .j av  a 2s. co m*/
        FileOutputStream fileOut = new FileOutputStream(filePath);
        Sheet worksheet = workbook.createSheet(table.getName());

        Row row1 = worksheet.createRow(0);

        Font keyFont = workbook.createFont();
        keyFont.setColor(HSSFColor.WHITE.index);
        keyFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        CellStyle keyCellStyle = workbook.createCellStyle();
        keyCellStyle.setFont(keyFont);
        keyCellStyle.setFillForegroundColor(HSSFColor.BLACK.index);
        keyCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        keyCellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        Key[] keys = null;
        String[][] values = null;
        if (ServletHelper.isJson()) {
            keys = table.getTableJson().getKeys();
            values = table.getTableJson().getValues();
        } else {
            keys = table.getKeys();
            values = table.getValues();
        }
        for (int i = 0; i < keys.length; i++) {
            Cell cell = row1.createCell(i);
            cell.setCellValue(keys[i].getName());
            cell.setCellStyle(keyCellStyle);
        }

        for (int i = 0; i < values.length; i++) {
            Row excelRow = worksheet.createRow(i + 1);
            for (int j = 0; j < values[i].length; j++) {
                Cell cell = excelRow.createCell(j);
                cell.setCellValue(values[i][j]);
            }
        }

        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
        return "success";
    } catch (Exception e) {
        return e.getLocalizedMessage();
    }
}

From source file:org.haplo.jsinterface.generate.KGenerateXLS.java

License:Mozilla Public License

@Override
protected void writeRow(int rowNumber, ArrayList<Object> row, ArrayList<Object> rowOptions, boolean isHeaderRow,
        boolean pageBreakBefore) {
    Row r = this.sheet.createRow(rowNumber);

    if (pageBreakBefore && rowNumber > 0) {
        this.sheet.setRowBreak(rowNumber - 1);
    }//from   w w  w  .ja v  a 2 s.com

    int rowSize = row.size();
    for (int i = 0; i < rowSize; ++i) {
        Object value = row.get(i); // ConsString is checked
        if (value != null) {
            Cell c = r.createCell(i);
            if (value instanceof Number) {
                c.setCellValue(((Number) value).doubleValue());
            } else if (value instanceof CharSequence) {
                c.setCellValue(((CharSequence) value).toString());
            } else if (value instanceof Date) {
                c.setCellValue((Date) value);
                // Check to see if option is for dates only
                boolean dateAndTimeStyle = true;
                String options = (String) getOptionsFromArrayList(rowOptions, i, String.class); // ConsString is checked by getOptionsFromArrayList()
                if (options != null && options.equals("date")) {
                    dateAndTimeStyle = false;
                }
                if (dateCellStyle == null) {
                    // Only create one each of the date cell styles per workbook to save space.
                    dateCellStyle = workbook.createCellStyle();
                    dateCellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm"));
                    dateOnlyCellStyle = workbook.createCellStyle();
                    dateOnlyCellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd"));
                }
                c.setCellStyle(dateAndTimeStyle ? dateCellStyle : dateOnlyCellStyle);
                // Set column width so the dates don't come out as ########## on causal viewing
                setMinimumWidth(i, dateAndTimeStyle ? DATE_AND_TIME_COLUMN_WIDTH : DATE_COLUMN_WIDTH);
            }
        }
    }

    if (isHeaderRow) {
        // Make sure the row is always on screen
        this.sheet.createFreezePane(0, 1, 0, 1);
        // Style the row
        CellStyle style = this.workbook.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);
        Font font = this.workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        r.setRowStyle(style);
        // Style the cells
        for (int s = 0; s < rowSize; ++s) {
            Cell c = r.getCell(s);
            if (c == null) {
                c = r.createCell(s);
            }
            c.setCellStyle(style);
        }
    }
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

@SuppressWarnings("unused")
private static void writeCell(Cell cell, Object val, boolean userTemplate,
        ExcelWriteFieldMappingAttribute attribute, Object bean) {
    if (attribute != null && attribute.getLinkField() != null) {
        String addressFieldName = attribute.getLinkField();
        String address = null;// ww  w.  java  2  s.co m
        if (bean != null) {
            address = (String) getFieldValue(bean, addressFieldName, true);
        }
        Workbook wb = cell.getRow().getSheet().getWorkbook();

        Hyperlink link = wb.getCreationHelper().createHyperlink(attribute.getLinkType());
        link.setAddress(address);
        cell.setHyperlink(link);
        // Its style can't inherit from cell.
        CellStyle style = wb.createCellStyle();
        Font hlinkFont = wb.createFont();
        hlinkFont.setUnderline(Font.U_SINGLE);
        hlinkFont.setColor(IndexedColors.BLUE.getIndex());
        style.setFont(hlinkFont);
        if (cell.getCellStyle() != null) {
            style.setFillBackgroundColor(cell.getCellStyle().getFillBackgroundColor());
        }
        cell.setCellStyle(style);
    }
    if (val == null) {
        cell.setCellValue((String) null);
        return;
    }
    Class<?> clazz = val.getClass();
    if (val instanceof Byte) {// Double
        Byte temp = (Byte) val;
        cell.setCellValue((double) temp.byteValue());
    } else if (val instanceof Short) {
        Short temp = (Short) val;
        cell.setCellValue((double) temp.shortValue());
    } else if (val instanceof Integer) {
        Integer temp = (Integer) val;
        cell.setCellValue((double) temp.intValue());
    } else if (val instanceof Long) {
        Long temp = (Long) val;
        cell.setCellValue((double) temp.longValue());
    } else if (val instanceof Float) {
        Float temp = (Float) val;
        cell.setCellValue((double) temp.floatValue());
    } else if (val instanceof Double) {
        Double temp = (Double) val;
        cell.setCellValue((double) temp.doubleValue());
    } else if (val instanceof Date) {// Date
        Date dateVal = (Date) val;
        long time = dateVal.getTime();
        // read is based on 1899/12/31 but DateUtil.getExcelDate is base on
        // 1900/01/01
        if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_01_00_00_00_000) {
            Date incOneDay = new Date(time + 24 * 60 * 60 * 1000);
            double d = DateUtil.getExcelDate(incOneDay);
            cell.setCellValue(d - 1);
        } else {
            cell.setCellValue(dateVal);
        }

        if (!userTemplate) {
            Workbook wb = cell.getRow().getSheet().getWorkbook();
            CellStyle cellStyle = cell.getCellStyle();
            if (cellStyle == null) {
                cellStyle = wb.createCellStyle();
            }
            DataFormat dataFormat = wb.getCreationHelper().createDataFormat();
            // @see #BuiltinFormats
            // 0xe, "m/d/yy"
            // 0x14 "h:mm"
            // 0x16 "m/d/yy h:mm"
            // {@linke https://en.wikipedia.org/wiki/Year_10,000_problem}
            /** [1899/12/31 00:00:00:000~1900/01/01 00:00:000) */
            if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_02_00_00_00_000) {
                cellStyle.setDataFormat(dataFormat.getFormat("h:mm"));
                // cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
            } else {
                // if ( time % (24 * 60 * 60 * 1000) == 0) {//for time
                // zone,we can't use this way.
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dateVal);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                int millisecond = calendar.get(Calendar.MILLISECOND);
                if (millisecond == 0 && second == 0 && minute == 0 && hour == 0) {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy"));
                } else {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
                }
            }
            cell.setCellStyle(cellStyle);
        }
    } else if (val instanceof Boolean) {// Boolean
        cell.setCellValue(((Boolean) val).booleanValue());
    } else {// String
        cell.setCellValue((String) val.toString());
    }
}

From source file:org.isatools.isacreatorconfigurator.configui.io.Utils.java

License:Open Source License

public static String createTableConfigurationEXL(String outputDir,
        Map<MappingObject, List<Display>> tableFields)
        throws DataNotCompleteException, InvalidFieldOrderException, IOException {

    String excelFileName = "ISA-config-template.xlsx";
    FileOutputStream fos = new FileOutputStream(outputDir + File.separator + excelFileName);

    String tableName = "";

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet hiddenSheet = workbook.createSheet("hiddenCV");

    Map<String, List<String>> nodups = new HashMap<String, List<String>>();
    XSSFSheet ontologyRestriction = workbook.createSheet("Restrictions");
    XSSFRow ontorow0 = ontologyRestriction.createRow((short) 0);

    ontorow0.createCell(0).setCellValue("Column Name");
    ontorow0.createCell(1).setCellValue("Ontology");
    ontorow0.createCell(2).setCellValue("Branch");
    ontorow0.createCell(3).setCellValue("Version");

    CreationHelper factory = workbook.getCreationHelper();

    //  int counting=0;
    //  int ontocounter=0;
    int lastposition = 0;

    for (MappingObject mo : tableFields.keySet()) {

        tableName = mo.getAssayName().replace("\\s", "");

        List<Display> elements = tableFields.get(mo);

        System.out.println("creating worksheet: " + tableName);

        //we create a table with 50 records by default for anything that is not an investigation file
        if (!tableName.contains("investigation")) {

            XSSFSheet tableSheet = workbook.createSheet(tableName);
            Drawing drawing = tableSheet.createDrawingPatriarch();
            CellStyle style = workbook.createCellStyle();
            XSSFRow rowAtIndex;//from   ww w  . j a v a2 s. co m

            //we create 51 rows by default for each table
            for (int index = 0; index <= 50; index++) {
                rowAtIndex = tableSheet.createRow((short) index);
            }

            //the first row is the header we need to build from the configuration declaration
            XSSFRow header = tableSheet.getRow(0);

            //we now iterated through the element found in the xml table configuration
            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {

                if (elements.get(fieldIndex).getFieldDetails() != null) {

                    if (elements.get(fieldIndex).getFieldDetails().isRequired() == true) {

                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.RED.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        System.out.println("REQUIRED field number " + fieldIndex + " is: "
                                + elements.get(fieldIndex).getFieldDetails().getFieldName());

                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);

                    } else {
                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.BLACK.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);
                    }

                    //checking if the field requires controled values, i.e ISA datatype is List

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.LIST) {

                        //create a hidden spreadsheet and named range with the list of val
                        //counting++; //incrementing the counter defining the position where to start the new namedrange in the hidden spreadsheet

                        //obtain the name of the ISA fields and extracting key information needed to create a unique name for the Named Range to be
                        String rangeName = elements.get(fieldIndex).getFieldDetails().getFieldName()
                                .replace("'", "").replace(" ", "").replace("Comment[", "")
                                .replace("ParameterValue[", "").replace("Characteristics[", "").replace("]", "")
                                .replace("(", "").replace(")", "");

                        //getting all the values allowed by the List Field
                        String[] fieldValues = elements.get(fieldIndex).getFieldDetails().getFieldList();

                        //System.out.println("CV : "+elements.get(fieldIndex).getFieldDetails().getFieldName()+ " values: "  + Arrays.asList(fieldValues).toString()+ "size :" +fieldValues.length);

                        //iterating through the values and creating a cell for each
                        for (int j = 0; j < fieldValues.length; j++) {
                            hiddenSheet.createRow(lastposition + j).createCell(0).setCellValue(fieldValues[j]);
                        }

                        Name namedCell = workbook.createName();

                        workbook.getNumberOfNames();

                        int k = 0;
                        int position = 0;

                        //this is to handle ISA Fields sharing the same name (in different assays)
                        //namedRanges in Excel must be unique

                        while (k < workbook.getNumberOfNames()) { //we can the total number of field to type list we have found so far.

                            //something already exists...
                            if (workbook.getNameAt(k).equals(rangeName)) {
                                // namedCell.setNameName(workbook.getNameAt(k).toString());
                                //no need to go further, we exit here and set the parameter position to use the value
                                position = k;
                                k = -1;
                            } else {
                                k++;
                            }
                        }

                        if (k > 0) { //this means this field already existed list of that type
                            //we name the new cell after it
                            namedCell.setNameName(rangeName + k);
                            System.out.println("Name Name: " + namedCell.getNameName());
                        } else { //there is already one, so we just point back to it using the position parameter
                            namedCell.setNameName(workbook.getNameAt(k).toString()); //workbook.getNameAt(position).toString()
                            System.out.println("Name Name: " + namedCell.getNameName());
                        }

                        int start = 0;
                        int end = 0;
                        start = lastposition + 1;
                        System.out.println("start: + " + start);
                        end = lastposition + fieldValues.length;
                        System.out.println("end: + " + end);

                        //                                    String reference ="hiddenCV"+"!"+convertNumToColString(0)+start+":"+ convertNumToColString(0)+end;
                        String reference = "hiddenCV" + "!$" + convertNumToColString(0) + "$" + start + ":$"
                                + convertNumToColString(0) + "$" + end;
                        namedCell.setRefersToFormula(reference);

                        start = 0;
                        end = 0;
                        DataValidationHelper validationHelper = new XSSFDataValidationHelper(tableSheet);
                        DataValidationConstraint constraint = validationHelper
                                .createFormulaListConstraint(reference);
                        CellRangeAddressList addressList = new CellRangeAddressList(1, 50, fieldIndex,
                                fieldIndex);

                        System.out.println("field index: " + fieldIndex);
                        DataValidation dataValidation = validationHelper.createValidation(constraint,
                                addressList);

                        tableSheet.addValidationData(dataValidation);

                        lastposition = lastposition + fieldValues.length;
                        System.out.println("lastposition: + " + lastposition);
                        System.out.println("reference: " + reference);
                    }

                    //                                //TODO: reformat date but this is pain in Excel
                    //                                if (elements.get(fieldIndex).getFieldDetails().getDatatype()== DataTypes.DATE) {
                    //                                    //do something
                    //                                }

                    //  If a default value has been specified in the ISAconfiguration, we set it in the Excel spreadsheet
                    if (elements.get(fieldIndex).getFieldDetails().getDefaultVal() != null) {
                        for (int i = 1; i < 51; i++) {
                            rowAtIndex = tableSheet.getRow(i);
                            XSSFCell cellThere = rowAtIndex.createCell(fieldIndex);
                            cellThere.setCellValue(elements.get(fieldIndex).getFieldDetails().getDefaultVal());
                        }
                    }

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.ONTOLOGY_TERM) {
                        int count = elements.get(fieldIndex).getFieldDetails().getRecommmendedOntologySource()
                                .values().size();
                        Collection<RecommendedOntology> myList = elements.get(fieldIndex).getFieldDetails()
                                .getRecommmendedOntologySource().values();
                        for (RecommendedOntology recommendedOntology : myList) {
                            System.out.println("ONTOLOGY :" + recommendedOntology.getOntology());
                            try {
                                if (recommendedOntology.getOntology() != null) {
                                    ArrayList<String> ontoAttributes = new ArrayList<String>();
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyID());
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyVersion());
                                    //  ontocounter++;
                                    //                                              XSSFRow ontoRowj = ontologyRestriction.createRow(ontocounter);
                                    //                                              ontoRowj.createCell(0).setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                                    //                                              ontoRowj.createCell(1).setCellValue(recommendedOntology.getOntology().getOntologyID());
                                    //                                              ontoRowj.createCell(3).setCellValue(recommendedOntology.getOntology().getOntologyVersion());

                                    if (recommendedOntology.getBranchToSearchUnder() != null) {
                                        System.out.println("ONTOLOGY BRANCH :"
                                                + recommendedOntology.getBranchToSearchUnder());
                                        //                                                  ontoRowj.createCell(2).setCellValue(recommendedOntology.getBranchToSearchUnder().toString());
                                        ontoAttributes
                                                .add(recommendedOntology.getBranchToSearchUnder().toString());
                                    } else {
                                        ontoAttributes.add("");
                                    }

                                    nodups.put(elements.get(fieldIndex).getFieldDetails().getFieldName(),
                                            ontoAttributes);
                                }
                            } catch (NullPointerException npe) {
                                System.out.println(npe);
                            }
                        }
                    }
                }
            }
        } else {

            //we now create with the Investigation Sheet
            XSSFSheet tableSheet = workbook.createSheet(tableName);

            Drawing drawing = tableSheet.createDrawingPatriarch();

            CellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();

            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
                XSSFRow row = tableSheet.createRow((short) fieldIndex);
                if (elements.get(fieldIndex).getFieldDetails() != null) {
                    XSSFCell cell = row.createCell(0);
                    //create the header field by setting to FieldName as Cell name
                    cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());

                    //using the ISA field description to create a Comment attached to the set
                    ClientAnchor anchor = factory.createClientAnchor();
                    Comment comment = drawing.createCellComment(anchor);
                    RichTextString rts = factory
                            .createRichTextString(elements.get(fieldIndex).getFieldDetails().getDescription());
                    comment.setString(rts);
                    cell.setCellComment(comment);
                    cell.setCellStyle(style);
                    tableSheet.autoSizeColumn(fieldIndex);

                    SheetConditionalFormatting sheetCF = tableSheet.getSheetConditionalFormatting();

                    //condition: if the output of the FIND function is equal to 1, then, set cell to a blue font
                    ConditionalFormattingRule rule = sheetCF
                            .createConditionalFormattingRule("FIND(Investigation,$A$1:$A$21)>1");
                    //ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(ComparisonOperator.) ;
                    FontFormatting font1 = rule.createFontFormatting();
                    font1.setFontStyle(false, true);
                    font1.setFontColorIndex(IndexedColors.BLUE.index);

                    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:A21") };

                    sheetCF.addConditionalFormatting(regions, rule);
                }
            }
            tableSheet.setSelected(true);
            workbook.setSheetOrder(tableName, 0);

        }
    }

    //writes the values of ontology resources used to restrict selection in ISA fields
    int compteur = 1;

    for (Map.Entry<String, List<String>> entry : nodups.entrySet()) {
        String key = entry.getKey();
        // Object value = entry.getValue();

        System.out.println("UNIQUE RESOURCE: " + key);
        XSSFRow ontoRowj = ontologyRestriction.createRow(compteur);
        ontoRowj.createCell(0).setCellValue(key);
        ontoRowj.createCell(1).setCellValue(entry.getValue().get(0));
        ontoRowj.createCell(2).setCellValue(entry.getValue().get(2));
        ontoRowj.createCell(3).setCellValue(entry.getValue().get(1));

        compteur++;

    }

    //moving support worksheet to be the rightmost sheets in the workbook.
    //if the table corresponds to the study sample table, we move it to first position
    if (tableName.toLowerCase().contains("studysample")) {
        workbook.setSheetOrder(tableName, 1);
    }
    workbook.setSheetOrder("hiddenCV", tableFields.keySet().size() + 1);
    workbook.setSheetOrder("Restrictions", tableFields.keySet().size() + 1);
    workbook.write(fos);
    fos.close();

    String message = "Files have been saved in ";

    if (outputDir.equals("")) {
        message += "this programs directory";
    } else {
        message += outputDir;
    }

    return message;
}

From source file:org.jaffa.qm.finder.apis.ExcelExportService.java

License:Open Source License

public static Workbook generateExcel(QueryServiceConfig master, QueryServiceConfig child, String sheetName)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    Workbook wb = null;//w  w w. j  av  a2 s  . co m
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new SXSSFWorkbook(100);
    }
    try {
        // Creating worksheet
        Sheet sheet = null;
        if (sheetName != null)
            sheet = wb.createSheet(sheetName);
        else
            sheet = wb.createSheet();

        // creating a custom palette for the workbook
        CellStyle style = wb.createCellStyle();
        style = wb.createCellStyle();

        // setting the foreground color to gray
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Setting the border for the cells
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setAlignment(CellStyle.ALIGN_CENTER);

        // setting font weight
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);

        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum);
        int colIndex = 0;
        for (Object o : master.getColumnModel()) {
            String columnTitle = (String) ((DynaBean) o).get("header");
            if (columnTitle == null || columnTitle.length() == 0)
                columnTitle = (String) ((DynaBean) o).get("mapping");

            headerRow.createCell(colIndex).setCellValue(columnTitle);
            Cell cell = headerRow.getCell(colIndex);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(colIndex);
            colIndex += 1;
        }

        // Generate the Excel output by creating a simple HTML table
        if (child != null) {
            for (Object o : child.getColumnModel()) {
                String columnTitle = (String) ((DynaBean) o).get("header");
                if (columnTitle == null || columnTitle.length() == 0)
                    columnTitle = (String) ((DynaBean) o).get("mapping");

                headerRow.createCell(colIndex).setCellValue(columnTitle);
                Cell cell = headerRow.getCell(colIndex);
                cell.setCellStyle(style);
                sheet.autoSizeColumn(colIndex);
                colIndex += 1;

            }
        }

        // Invoke the query and obtain an array of Graph objects
        Object[] queryOutput = invokeQueryService(master.getCriteriaClassName(), master.getCriteriaObject(),
                master.getServiceClassName(), master.getServiceClassMethodName());

        // Add the data rows
        if (queryOutput != null) {
            for (Object row : queryOutput) {
                Object[] detailQueryOutput = new Object[0];
                if (child == null) {
                    rowNum += 1;
                    Row dataRow = sheet.createRow((short) rowNum);
                    int colNum = 0;
                    // extract the columns from master object
                    for (Object o : master.getColumnModel()) {
                        String mapping = (String) ((DynaBean) o).get("mapping");
                        Object value = null;
                        if (mapping.startsWith("appFields.")) {
                            mapping = mapping.substring(10);
                            try {
                                Object[] appFields = (Object[]) PropertyUtils.getProperty(row,
                                        "applicationFields");
                                for (Object field : appFields) {
                                    String name = (String) PropertyUtils.getProperty(field, "name");
                                    if (name.equals(mapping)) {
                                        value = (String) PropertyUtils.getProperty(field, "value");
                                    }
                                }
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        } else {
                            try {
                                value = PropertyUtils.getProperty(row, mapping);
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        }
                        dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                        colNum += 1;
                    }
                } else { //child is not null
                    // load the child rows
                    String detailCriteriaObject = child.getCriteriaObject();
                    for (int i = 0; i < child.getMasterKeyFieldNames().length; i++) {
                        String kfn = child.getMasterKeyFieldNames()[i];
                        try {
                            String keyValue = (String) PropertyUtils.getProperty(row, kfn);
                            detailCriteriaObject = detailCriteriaObject.replace("{" + i + "}", keyValue);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Key property not found: " + kfn, e);
                        }
                    }
                    detailQueryOutput = invokeQueryService(child.getCriteriaClassName(), detailCriteriaObject,
                            child.getServiceClassName(), "query");

                    // add the child columns
                    if (detailQueryOutput != null && detailQueryOutput.length > 0) {
                        for (Object detailRow : detailQueryOutput) {
                            rowNum += 1;
                            Row dataRow = sheet.createRow((short) rowNum);

                            int colNum = 0;
                            // extract the columns from master object
                            for (Object obj : master.getColumnModel()) {
                                String masterMapping = (String) ((DynaBean) obj).get("mapping");
                                Object masterValue = null;
                                try {
                                    masterValue = PropertyUtils.getProperty(row, masterMapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found: " + masterMapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(masterValue, (DynaBean) obj));
                                colNum += 1;
                            }

                            for (Object o : child.getColumnModel()) {
                                String mapping = (String) ((DynaBean) o).get("mapping");
                                Object value = null;
                                try {
                                    value = PropertyUtils.getProperty(detailRow, mapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found in child result: " + mapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                                colNum += 1;
                            }
                        }
                    }
                }
            }
        }

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

From source file:org.jaffa.ria.finder.apis.ExcelExportService.java

License:Open Source License

public static Workbook generateExcel(QueryServiceConfig master, QueryServiceConfig child, String sheetName)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    Workbook wb = null;/*from ww  w . ja v a 2 s  .c  o  m*/
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new SXSSFWorkbook(100);
    }
    try {
        // Creating worksheet
        Sheet sheet = null;
        if (sheetName != null) {
            if (sheetName.length() > 31)
                sheetName = sheetName.substring(0, 31);
            char replaceChar = '_';
            sheetName = sheetName.replace('\u0003', replaceChar).replace(':', replaceChar)
                    .replace('/', replaceChar).replace("\\\\", Character.toString(replaceChar))
                    .replace('?', replaceChar).replace('*', replaceChar).replace(']', replaceChar)
                    .replace('[', replaceChar);
            sheet = wb.createSheet(sheetName);
        } else
            sheet = wb.createSheet();

        // creating a custom palette for the workbook
        CellStyle style = wb.createCellStyle();
        style = wb.createCellStyle();

        // setting the foreground color to gray
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Setting the border for the cells
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setAlignment(CellStyle.ALIGN_CENTER);

        // setting font weight
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);

        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum);
        int colIndex = 0;
        for (Object o : master.getColumnModel()) {
            String columnTitle = (String) ((DynaBean) o).get("header");
            if (columnTitle == null || columnTitle.length() == 0)
                columnTitle = (String) ((DynaBean) o).get("mapping");

            headerRow.createCell(colIndex).setCellValue(columnTitle);
            Cell cell = headerRow.getCell(colIndex);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(colIndex);
            colIndex += 1;
        }

        // Generate the Excel output by creating a simple HTML table
        if (child != null) {
            for (Object o : child.getColumnModel()) {
                String columnTitle = (String) ((DynaBean) o).get("header");
                if (columnTitle == null || columnTitle.length() == 0)
                    columnTitle = (String) ((DynaBean) o).get("mapping");

                headerRow.createCell(colIndex).setCellValue(columnTitle);
                Cell cell = headerRow.getCell(colIndex);
                cell.setCellStyle(style);
                sheet.autoSizeColumn(colIndex);
                colIndex += 1;

            }
        }

        // Invoke the query and obtain an array of Graph objects
        Object[] queryOutput = invokeQueryService(master.getCriteriaClassName(), master.getCriteriaObject(),
                master.getServiceClassName(), master.getServiceClassMethodName());

        // Add the data rows
        if (queryOutput != null) {
            for (Object row : queryOutput) {
                Object[] detailQueryOutput = new Object[0];
                if (child == null) {
                    rowNum += 1;
                    Row dataRow = sheet.createRow((short) rowNum);
                    int colNum = 0;
                    // extract the columns from master object
                    for (Object o : master.getColumnModel()) {
                        String mapping = (String) ((DynaBean) o).get("mapping");
                        Object value = null;
                        try {
                            value = PropertyUtils.getProperty(row, mapping);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Property not found: " + mapping, e);
                        }

                        dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                        colNum += 1;
                    }
                } else { //child is not null
                    // load the child rows
                    String detailCriteriaObject = child.getCriteriaObject();
                    for (int i = 0; i < child.getMasterKeyFieldNames().length; i++) {
                        String kfn = child.getMasterKeyFieldNames()[i];
                        try {
                            String keyValue = (String) PropertyUtils.getProperty(row, kfn);
                            detailCriteriaObject = detailCriteriaObject.replace("{" + i + "}", keyValue);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Key property not found: " + kfn, e);
                        }
                    }
                    detailQueryOutput = invokeQueryService(child.getCriteriaClassName(), detailCriteriaObject,
                            child.getServiceClassName(), "query");

                    // add the child columns
                    if (detailQueryOutput != null && detailQueryOutput.length > 0) {
                        for (Object detailRow : detailQueryOutput) {
                            rowNum += 1;
                            Row dataRow = sheet.createRow((short) rowNum);

                            int colNum = 0;
                            // extract the columns from master object
                            for (Object obj : master.getColumnModel()) {
                                String masterMapping = (String) ((DynaBean) obj).get("mapping");
                                Object masterValue = null;
                                try {
                                    masterValue = PropertyUtils.getProperty(row, masterMapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found: " + masterMapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(masterValue, (DynaBean) obj));
                                colNum += 1;
                            }

                            for (Object o : child.getColumnModel()) {
                                String mapping = (String) ((DynaBean) o).get("mapping");
                                Object value = null;
                                try {
                                    value = PropertyUtils.getProperty(detailRow, mapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found in child result: " + mapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                                colNum += 1;
                            }
                        }
                    }
                }
            }
        }

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

From source file:org.jboss.dashboard.displayer.table.ExportTool.java

License:Apache License

private Map<String, CellStyle> createStyles(Workbook wb) {
    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CellStyle style;

    Font titleFont = wb.createFont();
    titleFont.setFontHeightInPoints((short) 12);
    titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = wb.createCellStyle();/*from  w ww .  ja  v  a  2s  .co  m*/
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(titleFont);
    style.setWrapText(false);
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
    styles.put("header", style);

    Font cellFont = wb.createFont();
    cellFont.setFontHeightInPoints((short) 10);
    cellFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(3)));
    styles.put("integer_number_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(4)));
    styles.put("decimal_number_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat((short) BuiltinFormats.getBuiltinFormat("text"));
    styles.put("text_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat()
            .getFormat(DateFormatConverter.convert(LocaleManager.currentLocale(), dateFormatPattern)));
    styles.put("date_cell", style);
    return styles;
}

From source file:org.jcvi.ometa.utils.JsonProducer.java

License:Open Source License

public void jsonHelper(String projectNames, String attributes, String screenAttributes, String sorting,
        String fileName, String filePath, String domain) {
    String PROJECT_STATUS = "Project Status";
    try {/*  w w w. j a v a2  s.  co m*/
        JSONObject json = new JSONObject();

        File directory = new File(filePath);
        if (!directory.exists() || !directory.isDirectory()) {
            if ((new File(directory.getParent())).canWrite())
                directory.mkdir();
            else
                throw new Exception();
        }
        //Json file Creation
        File tempFile = new File(filePath + File.separator + fileName + "_temp.json");
        FileWriter fileWriter = new FileWriter(tempFile);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        //Normal status data retrieval
        LookupValue tempLookupValue;

        List<String> projectNameList = new ArrayList<String>();
        if (projectNames.contains(","))
            projectNameList.addAll(Arrays.asList(projectNames.split(",")));
        else
            projectNameList.add(projectNames);

        List<String> availableAttributes = new ArrayList<String>();
        availableAttributes.add("Sample Name");

        List<Project> projects = pseEjb.getProjects(projectNameList);
        List<Long> projectIds = new ArrayList<Long>();
        Map<String, Long> projectNameVsId = new HashMap<String, Long>();
        for (Project project : projects) {
            projectIds.add(project.getProjectId());
            projectNameVsId.put(project.getProjectName(), project.getProjectId());
        }

        List<ProjectMetaAttribute> allProjectMetaAttributes = pseEjb.getProjectMetaAttributes(projectIds);
        for (ProjectMetaAttribute pma : allProjectMetaAttributes) {
            if (!availableAttributes.contains(pma.getLookupValue().getName()))
                availableAttributes.add(pma.getLookupValue().getName());
        }
        List<SampleMetaAttribute> allSampleMetaAttributes = pseEjb.getSampleMetaAttributes(projectIds);
        for (SampleMetaAttribute sma : allSampleMetaAttributes) {
            if (!availableAttributes.contains(sma.getLookupValue().getName()))
                availableAttributes.add(sma.getLookupValue().getName());
        }
        List<EventMetaAttribute> allEventMetaAttributes = pseEjb.getEventMetaAttributes(projectIds);
        for (EventMetaAttribute ema : allEventMetaAttributes) {
            if (!availableAttributes.contains(ema.getLookupValue().getName()))
                availableAttributes.add(ema.getLookupValue().getName());
        }

        List<String> parameterizedAttributes = null;
        if (attributes == null || attributes.equals("") || "ALL".equals(attributes)) {
            parameterizedAttributes = availableAttributes;
        } else {
            parameterizedAttributes = new ArrayList<String>();

            ArrayList<String> tokenizedAttribute = new ArrayList<String>(Arrays.asList(attributes.split(",")));

            for (String tempAttribute : tokenizedAttribute) {
                if (availableAttributes.contains(tempAttribute))
                    parameterizedAttributes.add(tempAttribute);
            }
        }
        parameterizedAttributes.removeAll(Arrays.asList(forbiddenAttributes));

        /*------------ XLS Part ------------*/
        //Excel file Creation
        Workbook workBook = new HSSFWorkbook();
        Sheet workSheet = workBook.createSheet();
        int cellIndex = 0, rowIndex = 0;
        Row singleRow = workSheet.createRow(rowIndex++);
        Cell headerCell = null;

        //Header row cell style
        CellStyle style = workBook.createCellStyle();
        style.setFillBackgroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
        style.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        Font font = workBook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);
        /*------------ XLS Part END ------------*/

        List<String> attributeList = new ArrayList<String>();

        for (String tempAttribute : parameterizedAttributes) {
            attributeList.add(tempAttribute);
            headerCell = singleRow.createCell(cellIndex++);
            headerCell.setCellValue(tempAttribute);
            headerCell.setCellStyle(style);
        }

        if (screenAttributes == null || screenAttributes.equals("") || screenAttributes.equals("ALL")) {
            json.put("attributes", attributeList);
        } else {
            json.put("attributes", Arrays.asList(screenAttributes.split(",")));
        }

        json.put("sorting", (sorting == null || sorting.isEmpty() || sorting.equals("-") ? null : sorting));
        json.put("projectNames", projectNames);

        List<ProjectAttribute> allProjectAttributes = pseEjb.getProjectAttributes(projectIds);
        Map<Long, List<ProjectAttribute>> projIdVsAttributes = new HashMap<Long, List<ProjectAttribute>>();
        for (ProjectAttribute pa : allProjectAttributes) {
            List<ProjectAttribute> paList = projIdVsAttributes.get(pa.getProjectId());
            if (paList == null) {
                paList = new ArrayList<ProjectAttribute>();
                projIdVsAttributes.put(pa.getProjectId(), paList);
            }
            paList.add(pa);
        }

        List<Sample> allSamplesAllProjects = pseEjb.getSamplesForProjects(projectIds);
        Map<Long, List<Sample>> projectIdVsSampleList = new HashMap<Long, List<Sample>>();
        for (Sample sample : allSamplesAllProjects) {
            List<Sample> thisProjectsSamples = projectIdVsSampleList.get(sample.getProjectId());
            if (thisProjectsSamples == null) {
                thisProjectsSamples = new ArrayList<Sample>();
                projectIdVsSampleList.put(sample.getProjectId(), thisProjectsSamples);
            }
            thisProjectsSamples.add(sample);
        }

        /************* Main LOOP starts *****************/
        List<JSONObject> sampleList = new ArrayList<JSONObject>();
        List<String> statusList = new ArrayList<String>();
        List<JSONObject> sumList = new ArrayList<JSONObject>();

        for (Project project : projects) {
            JSONObject currSum = new JSONObject();

            if (project.getIsPublic() == 0)
                continue;

            Long tempProjectId = project.getProjectId();
            List<ProjectAttribute> paList = projIdVsAttributes.get(tempProjectId);
            Map<String, Object> projectAttrMap = new HashMap<String, Object>();
            if (paList != null) {
                for (ProjectAttribute pa : paList) {
                    ProjectMetaAttribute projectMeta = pa.getMetaAttribute();
                    tempLookupValue = projectMeta.getLookupValue();
                    projectAttrMap.put(tempLookupValue.getName(),
                            ModelValidator.getModelValue(tempLookupValue, pa));

                    if (projectMeta.getLabel() != null) { //add another key-value pair for a labeled attribute
                        projectAttrMap.put(projectMeta.getLabel(),
                                ModelValidator.getModelValue(tempLookupValue, pa));
                    }
                }
            }

            if (!projectAttrMap.containsKey(Constants.ATTR_PROJECT_NAME))
                projectAttrMap.put(Constants.ATTR_PROJECT_NAME, project.getProjectName());

            currSum.put("p_n", project.getProjectName());
            currSum.put("p_s", projectAttrMap.get(PROJECT_STATUS));
            currSum.put("p_g", projectAttrMap.get("Project Group"));

            List<Long> sampleIdList = getSampleIdList(getSamplesFromList(projectIdVsSampleList, tempProjectId));
            Map<Long, List<SampleAttribute>> sampleIdVsAttributeList = getSampleVsAttributeList(sampleIdList);
            Map<Long, List<Event>> sampleIdVsEventList = getSampleIdVsEventList(sampleIdList);

            List<Sample> samplesForProject = getSamplesFromList(projectIdVsSampleList, tempProjectId);
            currSum.put("tot", samplesForProject.size());

            for (Sample sample : samplesForProject) {
                Map<String, Object> sampleAttrMap = new HashMap<String, Object>();
                sampleAttrMap.putAll(projectAttrMap);
                sampleAttrMap.put(Constants.ATTR_SAMPLE_NAME, sample.getSampleName());
                sampleAttrMap.put("sampleId", sample.getSampleId());

                List<SampleAttribute> sampleAttributes = sampleIdVsAttributeList.get(sample.getSampleId());
                if (sampleAttributes != null && sampleAttributes.size() > 0) {
                    for (SampleAttribute sa : sampleAttributes) {
                        if (sa.getMetaAttribute() == null)
                            continue;
                        SampleMetaAttribute sampleMeta = sa.getMetaAttribute();
                        tempLookupValue = sampleMeta.getLookupValue();
                        Object sav = ModelValidator.getModelValue(tempLookupValue, sa);
                        sampleAttrMap.put(tempLookupValue.getName(), sav);

                        if (sampleMeta.getLabel() != null) { //add another key-value pair for a labeled attribute
                            sampleAttrMap.put(sampleMeta.getLabel(), sav);
                        }

                        if (SAMPLE_STATUS.equals(tempLookupValue.getName())) {
                            String currStatus = (String) sav;
                            if (!statusList.contains(currStatus)) //add new status value
                                statusList.add(currStatus);
                            currSum.put(currStatus,
                                    currSum.has(currStatus) ? currSum.getInt(currStatus) + 1 : 1); //count
                        }

                    }
                }

                List<Event> sampleEvents = sampleIdVsEventList.get(sample.getSampleId());
                if (sampleEvents != null && sampleEvents.size() > 0) {
                    Map<Long, List<EventAttribute>> eventIdVsAttributes = getEventIdVsAttributeList(
                            sampleEvents, tempProjectId);
                    //skip sample status value in event attributes
                    String[] skipArrForEventAttribute = { "Sample Status" };

                    for (Event evt : sampleEvents) {
                        List<EventAttribute> eventAttributes = eventIdVsAttributes.get(evt.getEventId());
                        if (eventAttributes == null)
                            continue;

                        sampleAttrMap.putAll(CommonTool.getAttributeValueMap(eventAttributes, false,
                                skipArrForEventAttribute));
                    }
                }

                if (!sampleAttrMap.containsKey("Organism")) { //manually add Organism attribute if not exist for GCID projects
                    sampleAttrMap.put("Organism", "");
                }

                JSONObject sampleJsonObj = new JSONObject();
                for (String key : sampleAttrMap.keySet()) {
                    //this is custom decorating process for json data file only
                    //in status.shtml page, link on an organism should land to the project page rather than sample detail page
                    if (key.equals("Organism")) {
                        String organismVal = (String) sampleAttrMap.get(key);
                        if (organismVal == null) { //get different attribute value for GCID projects
                            organismVal = (String) sampleAttrMap.get("Species Source Common Name(CS4)");
                        }

                        sampleJsonObj.put("OrganismUrl", (PROD_SERVER_ADDRESS + Constants.SAMPLE_DETAIL_URL
                                + "iss=true" + "&projectName=" + project.getProjectName() + "&projectId="
                                + project.getProjectId() + "&sampleName=" + sampleAttrMap.get("Sample Name")
                                + "&sampleId=" + sampleAttrMap.get("sampleId")).replaceAll("\\\"", "\\\\\""));
                        if (domain != null && !"none".equals(domain)) {
                            String projectGroup = (String) sampleAttrMap.get("Project Group");
                            organismVal = convertIntoATag(String.format(Constants.PROJECT_SPECIFIC_PAGE, domain, //hostName != null && hostName.contains("spike") ? fileName + "-dev" : fileName,
                                    (projectGroup == null ? "" : projectGroup.toLowerCase()),
                                    project.getProjectName().replaceAll(" ", "_")), organismVal);
                        }
                        sampleJsonObj.put(key, organismVal);
                    } else {
                        sampleJsonObj.put(key, CommonTool.decorateAttribute(sampleAttrMap, key, project));
                    }
                }
                sampleList.add(sampleJsonObj);

                cellIndex = 0;
                singleRow = workSheet.createRow(rowIndex++);
                for (String tempAttribute : parameterizedAttributes) {
                    singleRow.createCell(cellIndex++)
                            .setCellValue(sampleAttrMap.get(tempAttribute) != null
                                    ? "" + sampleAttrMap.get(tempAttribute)
                                    : "");
                }
            }
            sumList.add(currSum);
        }

        JSONObject sumMap = new JSONObject();
        sumMap.put("s_l", statusList);
        sumMap.put("data", sumList);
        json.put("sums", sumMap);

        json.put("samples", sampleList);
        //bufferedWriter.write("]");
        bufferedWriter.write(json.toString());
        bufferedWriter.close();

        if (tempFile.exists() && tempFile.length() > 0) {
            File dataFile = new File(filePath + File.separator + fileName + ".json");
            tempFile.renameTo(dataFile);

            FileOutputStream fileOut = new FileOutputStream(filePath + File.separator + fileName + ".xls");
            workBook.write(fileOut);
            fileOut.close();
        } else
            throw new Exception("Failure in retrieving data for " + fileName
                    + ". File does not exist or file size is zero.");

        logger.info("[JsonProducer-MBean] JsonProducer process succeeded for " + projectNames);
    } catch (Exception ex) {
        logger.info("[JsonProducer-MBean] JsonProducer failed for " + projectNames);
        ex.printStackTrace();

        /*if( hostName.contains( "dmzweb" ) ) { //Send error notification for DMZs only
        new EmailSender().send(
                "json",
                "[PST]Failure in generating Json Data file on : " + hostName,
                ex.toString()
        );
        }*/
    }
}