DynamicJasper:基于值的背景颜色

时间:2017-10-17 13:25:47

标签: java jasper-reports dynamic-jasper

是否可以使用DynamicJasper API为每行使用给定颜色设置特定单元格的背景颜色?

如果对象产品具有{id,price,name, color }属性 那么 name 字段的背景颜色需要更改为 color 字段的值。 (JasperReports支持此行为)

1 个答案:

答案 0 :(得分:0)

<强>指南:

在此解决方案中,在创建报告之前会生成所有可能颜色的列表。 colorCell列具有自己的值以及颜色值(表示为字段)。 所有颜色都是HexString。 DynamicJasperReport.java

   public class DynamicJasperReport{
     public DynamicJasperReport(List<String> color){
        DynamicReportBuilder drb = new DynamicReportBuilder();
        ArrayList<ConditionalStyle> listCondStyle = StyleUtils.getConditonalStyles(color);
        AbstractColumn col = ColumnBuilder.getNew()
                            .setColumnProperty("colordCell", Object.class.getName())
                            .setTitle("Colored Cell")
                            .addConditionalStyles(listCondStyle)
                            .build();
   //adding the color value
        drb.addField("color", Boolean.class.getName());
    }


   }

<强> ConditionStyleExpression: BackgroundCondition.java

   public class BackgroundCondition  extends ConditionStyleExpression implements CustomExpression {
       private String fieldName;
       private String colorValue;

       public BackgroundCondition(String fieldName, String colorValue) {
    this.fieldName = fieldName;
    this.colorValue = colorValue;
}

       public Object evaluate(Map fields, Map variables, Map parameters) {
    boolean condition = false;
    Object currentValue = fields.get(fieldName);
    if (currentValue instanceof String) {
        String s = (String) currentValue;
        condition = colorValue.equals(currentValue);
    }
    return condition;
}

       public String getClassName() {
         return Boolean.class.getName();
      }
   }

StyleUtils.java:

  public abstract class StyleUtils {
   public static Style backgroundColorStyle (String hexColor){
     Style cellBackgroundStyle = new Style();
     cellBackgroundStyle.setTransparency(Transparency.OPAQUE);
     cellBackgroundStyle.setBackgroundColor(Color.decode(hexColor));
     cellBackgroundStyle.setTextColor(Color.BLACK);
     cellBackgroundStyle.setVerticalAlign(VerticalAlign.TOP);
     return cellBackgroundStyle;
    }

   public static ArrayList<ConditionalStyle> getConditonalStyles(List<String> Color) {
    ArrayList<ConditionalStyle> conditionalStyles = new ArrayList<ConditionalStyle>();
    Color.forEach(c-> {
        BackgroundCondition backgroundCondition = new BackgroundCondition("color", c);
        ConditionalStyle cs = new ConditionalStyle(backgroundCondition, StyleUtils.backgroundColorStyle(c));
        conditionalStyles.add(cs);

    });
    return conditionalStyles;
}
  }