Example usage for org.apache.poi.ss.usermodel Workbook createFont

List of usage examples for org.apache.poi.ss.usermodel Workbook createFont

Introduction

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

Prototype

Font createFont();

Source Link

Document

Create a new Font and add it to the workbook's font table

Usage

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

License:Apache License

public static CellStyle getDefaultDetailCellStyle(Workbook wb, Boolean defaultFormat) {
    CellStyle detailCellStyle = null;//from  w w w .java2  s  .co  m
    if (defaultFormat != null && defaultFormat) {
        //Armamos el formato para los datos del detalle
        detailCellStyle = wb.createCellStyle();
        Font detailFont = wb.createFont();
        detailFont.setFontHeightInPoints((short) 8);
        detailCellStyle.setFont(detailFont);
    }
    return detailCellStyle;
}

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

License:Apache License

public static CellStyle getDefaultHeaderCellStyle(Workbook wb, Boolean defaultFormat) {
    CellStyle headerCellStyle = null;/*w w w  . ja v  a 2s.co m*/
    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);
    }
    return headerCellStyle;
}

From source file:org.geoserver.wfs.response.ExcelCellStyles.java

License:Open Source License

public ExcelCellStyles(Workbook wb) {
    CreationHelper helper = wb.getCreationHelper();
    DataFormat fmt = helper.createDataFormat();

    dateStyle = wb.createCellStyle();/*from w w  w  .j av a  2 s  .  c  om*/
    dateStyle.setDataFormat(fmt.getFormat("yyyy-mm-dd hh:mm:ss"));

    headerStyle = wb.createCellStyle();
    Font headerFont = wb.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerStyle.setFont(headerFont);

    warningStyle = wb.createCellStyle();
    Font warningFont = wb.createFont();
    warningFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    warningFont.setColor(Font.COLOR_RED);
    warningStyle.setFont(warningFont);
}

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;/*from   ww w .java  2s  .  c  o 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.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;
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {//from  ww w . ja  v  a2s. co  m
        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;
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {// w w  w.  j  a va 2s  .c  o m
        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;/*from   w w w.j  ava  2 s  .co  m*/

    Font titleFont = wb.createFont();
    titleFont.setFontHeightInPoints((short) 12);
    titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = wb.createCellStyle();
    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 {//from www.  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()
        );
        }*/
    }
}

From source file:org.joeffice.spreadsheet.TableStyleable.java

License:Apache License

private Font copyFont(Cell cell) {
    CellStyle style = cell.getCellStyle();
    Workbook workbook = cell.getSheet().getWorkbook();
    short fontIndex = style.getFontIndex();
    Font xlsFont = cell.getSheet().getWorkbook().getFontAt(fontIndex);
    Font newFont = workbook.createFont();
    newFont.setFontName(xlsFont.getFontName());
    newFont.setFontHeight((short) xlsFont.getFontHeight());
    newFont.setBoldweight(xlsFont.getBoldweight());
    newFont.setItalic(xlsFont.getItalic());
    newFont.setUnderline(xlsFont.getUnderline());
    newFont.setColor(xlsFont.getColor());
    return newFont;
}

From source file:org.kuali.test.runner.output.PoiHelper.java

License:Educational Community License

private void createPoiCellStyles(Workbook workbook) {

    // create bold cell style
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleBold = workbook.createCellStyle();
    cellStyleBold.setFont(font);/*w  ww.ja  v  a 2 s . co  m*/

    // create standard cell style
    font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
    font.setFontHeightInPoints((short) 10);
    cellStyleNormal = workbook.createCellStyle();
    cellStyleNormal.setFont(font);
    cellStyleNormal.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create test header cell style
    font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleTestHeader = workbook.createCellStyle();
    cellStyleTestHeader.setFont(font);
    cellStyleTestHeader.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.index);
    cellStyleTestHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);

    // create timestamp cell style
    font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
    font.setFontHeightInPoints((short) 10);
    cellStyleTimestamp = workbook.createCellStyle();
    cellStyleTimestamp.setFont(font);
    cellStyleTimestamp.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
    cellStyleTimestamp.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create timestamp cell style
    font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
    font.setFontHeightInPoints((short) 10);
    cellStyleTime = workbook.createCellStyle();
    cellStyleTime.setFont(font);
    cellStyleTime.setDataFormat(workbook.createDataFormat().getFormat("hh:mm:ss"));
    cellStyleTime.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create success cell style
    font = workbook.createFont();
    font.setColor(IndexedColors.DARK_GREEN.index);
    font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
    font.setFontHeightInPoints((short) 10);
    cellStyleSuccess = workbook.createCellStyle();
    cellStyleSuccess.setFont(font);
    cellStyleSuccess.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create ignore cell style
    font = workbook.createFont();
    font.setColor(IndexedColors.BROWN.index);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleIgnore = workbook.createCellStyle();
    cellStyleIgnore.setFont(font);
    cellStyleIgnore.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create warning cell style
    font = workbook.createFont();
    font.setColor(IndexedColors.DARK_YELLOW.index);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleWarning = workbook.createCellStyle();
    cellStyleWarning.setFont(font);
    cellStyleWarning.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create error cell style
    font = workbook.createFont();
    font.setColor(IndexedColors.DARK_RED.index);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleError = workbook.createCellStyle();
    cellStyleError.setFont(font);
    cellStyleError.setVerticalAlignment(CellStyle.VERTICAL_TOP);

    // create header cell style
    font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 10);
    cellStyleHeader = (XSSFCellStyle) workbook.createCellStyle();
    cellStyleHeader.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.index);
    cellStyleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);
    cellStyleHeader.setFont(font);
}