Home » excel » ruby on rails – Use different color for different values in drop down for excel files created

ruby on rails – Use different color for different values in drop down for excel files created

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need to create an excel sheet with a field status. It is a drop down with values ‘High’, ‘Medium’, and ‘Low’. I need to show different colors when they select different values. I have implemented the drop down using writeexcel gem. Here is my code:

worksheet.data_validation(count, 5,
          {
            :validate        => 'list',
            :source          => ['High', 'Medium', 'Low'],
          })

The drop down is working fine. But I want to specify a color for each selection. I can color the cell based on the selection of the dropdown, but what I need is different colors for different selections of the drop down. Any other gem having this implementation is also fine.

How to&Answers:

The write_xlsx gem is an updated version of writeexcel that supports the newer Excel 2007+ XLSX format. It is by the same author and has the same interface but has additional features.

One of these new features is Conditional Formating.

You can use it to apply conditional formats to the same cell as the drop-down validation like this:

worksheet.conditional_formatting(count, 5,
    {
        :type     => 'cell',
        :format   => format1,
        :criteria => '=',
        :value    => '"High"'
    }
)

worksheet.conditional_formatting(count, 5,
    {
        :type     => 'cell',
        :format   => format2,
        :criteria => '=',
        :value    => '"Medium"'
    }
)
...

You will need to define the formats using the standard interface.

Note, write_xlsx is a port of the Perl module Excel::Writer::XLSX. That module contains additional documentation on the use of conditional formats. You should be able to convert the examples to Ruby easily enough.

See also my answer to your previous question.