How can I color every other row in my ODS HTML, PDF, and RTF output?


This KB article provides two methods of coloring every other row of a table. The sample code routes output to the ODS HTML destination. However, this logic is applicable in other non-Listing destinations as well.

PROC REPORT

You can use the automatic variable _ROW_ in a PROC REPORT CALL DEFINE statement to format every other row in your table. Here, a counter is created with a temporary variable so that you have a number on each observation. The MOD function is used to create the condition to change the background color of every other row to yellow.

ods html file='report.html'(title="Every other row") path=".";
proc report data=sashelp.cars(obs=10) nowd;
   compute type;
      count+1;
      if mod(count,2) then do;
         call define(_row_, "style", "style=[background=yellow]");
      end;
   endcomp;
run;
ods html close;

Results created with SAS® 9.4:

Table showing every other row highlighted in yellow (beginning with yellow)

The DATA Step

For procedures with table templates, you can use the DATA step to highlight every other row. The example below uses the CELLSTYLE statement with the MOD function. The variable I controls the background color of the odd rows, and the TEST statement binds the data with the template.

data temp;
   set sashelp.class ;
   i=_n_;
run; 

ods html file="datastep.html" path=".";

proc template;
   define table x;
     column i name age sex height weight;
     define i;  print=off;  end;
     cellstyle mod(i,2) as {background=pink};
   end;
   test data=temp;
run;

ods html close;

Results created with SAS 9.4:

A table showing a list of names in rows alternating red and white