How to color the cell in SAP ALV Display?

The old ALV Display model created using CL_GUI_ALV_GRID enables the user to colour particular cells of ALV Display. Every colour is uniquely identified through a colour code. The following table illustrates the different colour codes.

Type of colourCOLINTINV
Orange711
Green510
Red610
Yellow310
Blue110
Fig. Color codes for cells of ALV Display

The above fields COL,INT,INV are the elements of [lvc_s_scol – COLOR].

There are three key steps involved in colouring a particular cell / column of a SAP ALV Display.

  1. Extend the Internal table with the column lvc_t_scol.
  2. Assignment of column ‘lvc_t_scol’ to the field ‘CTAB_FNAME’ of layout.
  3. Assign the colour codes to the cells of SAP ALV Display.
  • Extension of Internal table.

The internal table which contains the data of the ALV Display is extended with the additional column ‘lvc_t_scol’. The table lvc_t_scol holds the details of the colour code. Let us look at the following structure extension.

TYPES: BEGIN OF ty_contact.

              INCLUDE STRUCTURE ztt_db_table2.

              TYPES: cell_with_color TYPE lvc_t_scol,

            END OF ty_contact.

DATA lt_contact TYPE TABLE OF ty_contact.

  • ASSIGNMENT of field ‘CTAB_FNAME’ to the layout.

The ALV Table recognizes the newly added field of type ‘LVC_T_SCOL’ through the field ‘CTAB_FNAME’ of the layout structure.

DATA ls_layout TYPE lvc_s_layo.

ls_layout-ctab_fname = ‘CELL_WITH_COLOR’.

the above value must be specified in capital letters. otherwise the ALV Grid cannot recognize the newly added field.

  • Assignment of Colour code to the cells of ALV Display.

The final step is to assign the colour codes to the cells of the ALV Table Display. The column is mentioned through the field ‘FNAME’ of the structure ‘lvc_s_scol’.

FIELD-SYMBOLS <ls_contact> TYPE ty_contact.

DATA ls_cell_color TYPE lvc_s_scol.

LOOP AT lt_contact ASSIGNING <ls_contact> WHERE age > 30.

              ls_cell_color-fname = ‘CONTACT_NAME’.

              ls_cell_color-col = 7.

              ls_cell_color-int= 1.

              ls_cell_color-inv = 1.

              APPEND ls_cell_color TO <ls_contact>-cell_with_color.

“The internal table is filled with color code details.

ENDLOOP.

              The above code snippet sets the colour of the ALV Cells. It is constrained to the contacts whose age are more than 30. The column specified here to be colored is ‘CONTACT_NAME’.