Example usage for org.apache.poi.ss.usermodel SheetConditionalFormatting addConditionalFormatting

List of usage examples for org.apache.poi.ss.usermodel SheetConditionalFormatting addConditionalFormatting

Introduction

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

Prototype

int addConditionalFormatting(CellRangeAddress[] regions, ConditionalFormattingRule[] cfRules);

Source Link

Document

Add a new Conditional Formatting set to the sheet.

Usage

From source file:org.aio.handy.poi.ConditionalFormats.java

License:Apache License

/**
 * Use Excel conditional formatting to shade alternating rows on the
 * worksheet/*  www.  j a v  a2s .  c o m*/
 */
static void shadeAlt(Sheet sheet) {
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    // Condition 1: Formula Is =A2=A1 (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

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

    sheetCF.addConditionalFormatting(regions, rule1);

    sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");
    sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is  =MOD(ROW(),2)   (Light Green Fill)");
}

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  w w  w . j a v  a2s  .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:packtest.ConditionalFormats.java

License:Apache License

/**
 * Multiple conditional formatting rules can apply to
 *  one cell, some combining, some beating others.
 * Done in order of the rules added to the 
 *  SheetConditionalFormatting object//  ww w.ja  va2s  .  c om
 */
static void overlapping(Sheet sheet) {
    for (int i = 0; i < 40; i++) {
        int rn = i + 1;
        Row r = sheet.createRow(i);
        r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")");
        String str = "";
        if (rn % 2 == 0)
            str = str + "even ";
        if (rn % 3 == 0)
            str = str + "x3 ";
        if (rn % 5 == 0)
            str = str + "x5 ";
        if (rn % 10 == 0)
            str = str + "x10 ";
        if (str.length() == 0)
            str = "nothing special...";
        r.createCell(1).setCellValue("It is " + str);
    }
    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);

    sheet.getRow(1).createCell(3).setCellValue("Even rows are blue");
    sheet.getRow(2).createCell(3).setCellValue("Multiples of 3 have a grey background");
    sheet.getRow(4).createCell(3).setCellValue("Multiples of 5 are bold");
    sheet.getRow(9).createCell(3).setCellValue("Multiples of 10 are red (beats even)");

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    // Condition 1: Row divides by 10, red (will beat #1)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),10)=0");
    FontFormatting font1 = rule1.createFontFormatting();
    font1.setFontColorIndex(IndexedColors.RED.index);

    // Condition 2: Row is even, blue
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)=0");
    FontFormatting font2 = rule2.createFontFormatting();
    font2.setFontColorIndex(IndexedColors.BLUE.index);

    // Condition 3: Row divides by 5, bold
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("MOD(ROW(),5)=0");
    FontFormatting font3 = rule3.createFontFormatting();
    font3.setFontStyle(false, true);

    // Condition 4: Row divides by 3, grey background
    ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule("MOD(ROW(),3)=0");
    PatternFormatting fill4 = rule4.createPatternFormatting();
    fill4.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);
    fill4.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    // Apply
    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:F41") };

    sheetCF.addConditionalFormatting(regions, rule1);
    sheetCF.addConditionalFormatting(regions, rule2);
    sheetCF.addConditionalFormatting(regions, rule3);
    sheetCF.addConditionalFormatting(regions, rule4);
}

From source file:packtest.ConditionalFormats.java

License:Apache License

/**
 * Icon Sets / Multi-States allow you to have icons shown which vary
 *  based on the values, eg Red traffic light / Yellow traffic light /
 *  Green traffic light/* w  ww .j  a  va2 s  .c  o  m*/
 */
static void iconSets(Sheet sheet) {
    sheet.createRow(0).createCell(0).setCellValue("Icon Sets");
    Row r = sheet.createRow(1);
    r.createCell(0).setCellValue("Reds");
    r.createCell(1).setCellValue(0);
    r.createCell(2).setCellValue(0);
    r.createCell(3).setCellValue(0);
    r = sheet.createRow(2);
    r.createCell(0).setCellValue("Yellows");
    r.createCell(1).setCellValue(5);
    r.createCell(2).setCellValue(5);
    r.createCell(3).setCellValue(5);
    r = sheet.createRow(3);
    r.createCell(0).setCellValue("Greens");
    r.createCell(1).setCellValue(10);
    r.createCell(2).setCellValue(10);
    r.createCell(3).setCellValue(10);

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("B1:B4") };
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(IconSet.GYR_3_TRAFFIC_LIGHTS);
    IconMultiStateFormatting im1 = rule1.getMultiStateFormatting();
    im1.getThresholds()[0].setRangeType(RangeType.MIN);
    im1.getThresholds()[1].setRangeType(RangeType.PERCENT);
    im1.getThresholds()[1].setValue(33d);
    im1.getThresholds()[2].setRangeType(RangeType.MAX);
    sheetCF.addConditionalFormatting(regions, rule1);

    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("C1:C4") };
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(IconSet.GYR_3_FLAGS);
    IconMultiStateFormatting im2 = rule1.getMultiStateFormatting();
    im2.getThresholds()[0].setRangeType(RangeType.PERCENT);
    im2.getThresholds()[0].setValue(0d);
    im2.getThresholds()[1].setRangeType(RangeType.PERCENT);
    im2.getThresholds()[1].setValue(33d);
    im2.getThresholds()[2].setRangeType(RangeType.PERCENT);
    im2.getThresholds()[2].setValue(67d);
    sheetCF.addConditionalFormatting(regions, rule2);

    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("D1:D4") };
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule(IconSet.GYR_3_SYMBOLS_CIRCLE);
    IconMultiStateFormatting im3 = rule1.getMultiStateFormatting();
    im3.setIconOnly(true);
    im3.getThresholds()[0].setRangeType(RangeType.MIN);
    im3.getThresholds()[1].setRangeType(RangeType.NUMBER);
    im3.getThresholds()[1].setValue(3d);
    im3.getThresholds()[2].setRangeType(RangeType.NUMBER);
    im3.getThresholds()[2].setValue(7d);
    sheetCF.addConditionalFormatting(regions, rule3);
}

From source file:packtest.ConditionalFormats.java

License:Apache License

/**
 * Color Scales / Colour Scales / Colour Gradients allow you shade the
 *  background colour of the cell based on the values, eg from Red to
 *  Yellow to Green.//ww w  .  java2 s. com
 */
static void colourScales(Sheet sheet) {
    sheet.createRow(0).createCell(0).setCellValue("Colour Scales");
    Row r = sheet.createRow(1);
    r.createCell(0).setCellValue("Red-Yellow-Green");
    for (int i = 1; i <= 7; i++) {
        r.createCell(i).setCellValue((i - 1) * 5);
    }
    r = sheet.createRow(2);
    r.createCell(0).setCellValue("Red-White-Blue");
    for (int i = 1; i <= 9; i++) {
        r.createCell(i).setCellValue((i - 1) * 5);
    }
    r = sheet.createRow(3);
    r.createCell(0).setCellValue("Blue-Green");
    for (int i = 1; i <= 16; i++) {
        r.createCell(i).setCellValue((i - 1));
    }
    sheet.setColumnWidth(0, 5000);

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("B2:H2") };
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingColorScaleRule();
    ColorScaleFormatting cs1 = rule1.getColorScaleFormatting();
    cs1.getThresholds()[0].setRangeType(RangeType.MIN);
    cs1.getThresholds()[1].setRangeType(RangeType.PERCENTILE);
    cs1.getThresholds()[1].setValue(50d);
    cs1.getThresholds()[2].setRangeType(RangeType.MAX);
    ((ExtendedColor) cs1.getColors()[0]).setARGBHex("FFF8696B");
    ((ExtendedColor) cs1.getColors()[1]).setARGBHex("FFFFEB84");
    ((ExtendedColor) cs1.getColors()[2]).setARGBHex("FF63BE7B");
    sheetCF.addConditionalFormatting(regions, rule1);

    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("B3:J3") };
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingColorScaleRule();
    ColorScaleFormatting cs2 = rule2.getColorScaleFormatting();
    cs2.getThresholds()[0].setRangeType(RangeType.MIN);
    cs2.getThresholds()[1].setRangeType(RangeType.PERCENTILE);
    cs2.getThresholds()[1].setValue(50d);
    cs2.getThresholds()[2].setRangeType(RangeType.MAX);
    ((ExtendedColor) cs2.getColors()[0]).setARGBHex("FFF8696B");
    ((ExtendedColor) cs2.getColors()[1]).setARGBHex("FFFCFCFF");
    ((ExtendedColor) cs2.getColors()[2]).setARGBHex("FF5A8AC6");
    sheetCF.addConditionalFormatting(regions, rule2);

    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("B4:Q4") };
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingColorScaleRule();
    ColorScaleFormatting cs3 = rule3.getColorScaleFormatting();
    cs3.setNumControlPoints(2);
    cs3.getThresholds()[0].setRangeType(RangeType.MIN);
    cs3.getThresholds()[1].setRangeType(RangeType.MAX);
    ((ExtendedColor) cs3.getColors()[0]).setARGBHex("FF5A8AC6");
    ((ExtendedColor) cs3.getColors()[1]).setARGBHex("FF63BE7B");
    sheetCF.addConditionalFormatting(regions, rule3);
}

From source file:packtest.ConditionalFormats.java

License:Apache License

/**
 * DataBars / Data-Bars allow you to have bars shown vary
 *  based on the values, from full to empty
 *///from  w  w w.  j av  a2 s. c  o  m
static void dataBars(Sheet sheet) {
    sheet.createRow(0).createCell(0).setCellValue("Data Bars");
    Row r = sheet.createRow(1);
    r.createCell(1).setCellValue("Green Positive");
    r.createCell(2).setCellValue("Blue Mix");
    r.createCell(3).setCellValue("Red Negative");
    r = sheet.createRow(2);
    r.createCell(1).setCellValue(0);
    r.createCell(2).setCellValue(0);
    r.createCell(3).setCellValue(0);
    r = sheet.createRow(3);
    r.createCell(1).setCellValue(5);
    r.createCell(2).setCellValue(-5);
    r.createCell(3).setCellValue(-5);
    r = sheet.createRow(4);
    r.createCell(1).setCellValue(10);
    r.createCell(2).setCellValue(10);
    r.createCell(3).setCellValue(-10);
    r = sheet.createRow(5);
    r.createCell(1).setCellValue(5);
    r.createCell(2).setCellValue(5);
    r.createCell(3).setCellValue(-5);
    r = sheet.createRow(6);
    r.createCell(1).setCellValue(20);
    r.createCell(2).setCellValue(-10);
    r.createCell(3).setCellValue(-20);
    sheet.setColumnWidth(0, 3000);
    sheet.setColumnWidth(1, 5000);
    sheet.setColumnWidth(2, 5000);
    sheet.setColumnWidth(3, 5000);

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    ExtendedColor color = sheet.getWorkbook().getCreationHelper().createExtendedColor();
    color.setARGBHex("FF63BE7B");
    CellRangeAddress[] regions = { CellRangeAddress.valueOf("B2:B7") };
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(color);
    DataBarFormatting db1 = rule1.getDataBarFormatting();
    db1.getMinThreshold().setRangeType(RangeType.MIN);
    db1.getMaxThreshold().setRangeType(RangeType.MAX);
    sheetCF.addConditionalFormatting(regions, rule1);

    color = sheet.getWorkbook().getCreationHelper().createExtendedColor();
    color.setARGBHex("FF5A8AC6");
    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("C2:C7") };
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(color);
    DataBarFormatting db2 = rule2.getDataBarFormatting();
    db2.getMinThreshold().setRangeType(RangeType.MIN);
    db2.getMaxThreshold().setRangeType(RangeType.MAX);
    sheetCF.addConditionalFormatting(regions, rule2);

    color = sheet.getWorkbook().getCreationHelper().createExtendedColor();
    color.setARGBHex("FFF8696B");
    regions = new CellRangeAddress[] { CellRangeAddress.valueOf("D2:D7") };
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule(color);
    DataBarFormatting db3 = rule3.getDataBarFormatting();
    db3.getMinThreshold().setRangeType(RangeType.MIN);
    db3.getMaxThreshold().setRangeType(RangeType.MAX);
    sheetCF.addConditionalFormatting(regions, rule3);
}