ruby-on-railsrubyaxlsx

Rails Axlsx render conditional row background color


I am using axlsx gem to generate Excel sheets in Ruby on Rails.

   wb = xlsx_package.workbook

   wb.styles do |s|
       title = s.add_style :b => true, :sz => 10,
           :border => { :style => :thin, :color => "00" },
           :alignment => {
              :horizontal => :center,
              :vertical => :center
           }
       row = s.add_style :b => false,
             :sz => 10,
             :border => { :style => :thin, :color => "00" },
             :alignment => {
                :horizontal => :left,
                :vertical => :center
             }


       wb.add_worksheet(name: "Customer") do |sheet|
       sheet.add_row ['Customer Name', 'Status'] :style => title
       @customers.each do |customer|
          sheet.add_row [customer.name, customer.status] :style => row
       end
   end

how can I conditionally change the row background color if the customer status let say = "Late Payment"


Solution

  • I haven't tested it but this should do the job.

    wb = xlsx_package.workbook
    
    wb.styles do |s|
       title = s.add_style :b => true, :sz => 10,
               :border => { :style => :thin, :color => "00" },
               :alignment => {
                 :horizontal => :center,
                 :vertical => :center
               }
       row = s.add_style :b => false,
             :sz => 10,
             :border => { :style => :thin, :color => "00" },
             :alignment => {
                :horizontal => :left,
                :vertical => :center
             }
    
       red_cell_row = s.add_style :b => false,
                      :sz => 10,
                      :border => { :style => :thin, :color => "00" },
                      :alignment => {
                        :horizontal => :left,
                        :vertical => :center
                      },
                      :bg_color => "FF0000", 
                      :fg_color => "000000"
    
       wb.add_worksheet(name: "Customer") do |sheet|
       sheet.add_row ['Customer Name', 'Status'] :style => title
       @customers.each do |customer|
          if customer.status == "Late Payment"
            sheet.add_row [customer.name, customer.status] :style => red_cell_row
          else
            sheet.add_row [customer.name, customer.status] :style => row
          end
       end
    end