How to give a date a background color with axlsx?

后端 未结 1 1646
忘掉有多难
忘掉有多难 2021-01-29 01:27

I create an excel with axslx. One row should be colored. But if I do so, I loose the date format for my dates.

Minimal example with some attempts I did:

         


        
相关标签:
1条回答
  • 2021-01-29 01:45

    You will need to specify the number format as well so your style would look like

    style1 = ws.styles.add_style(:bg_color => "EF0920", :fg_color => "FFFFFF", :format_code => "dd.mm.yyyy")
    

    When adding a style it will overwrite the default style and all formatting. e.g.

    ws.add_row [ Date.today, "Style with colors --The date is no date any longer"], :style => [style1,nil]
    

    This will produce a red date formatted like the other rows and a no fill column B.

    This style will be for the date only so if you want the whole column I would recommend something like

    red_style_h  = {:bg_color => "EF0920", :fg_color => "FFFFFF"} 
    red_date_h = red_style_h.merge(:format_code => "dd.mm.yyyy")
    
    red_style = ws.styles.add_style(red_style_h)
    red_date_style = ws.styles.add_style(red_date_h)
    

    Then style your rows as

    ws.add_row [ Date.today, "Style with colors --The date is no date any longer"], :style => [red_date_style,red_style]
    

    This will produce a red row (columns A and B) with the date formatted the same as the other rows.

    Git Hub Source

    There are also predefined styles available through numFmts and the global named constants NUM_FMT_PERCENTAGE,NUM_FMT_YYYYMMDD,NUM_FMT_YYYYMMDDHHMMSS, etc.

    When defining many different formats I find it easiest to use a YML file and then parse that to define styles e.g.

    red_style:&red
      bg_color: "EF0920"
      fg_color: "FFFFFF"
    red_date: 
      <<: *red
      format_code: dd.mm.yyyy
    

    Then something like

    class MyStylizedSheet < ::Axlsx::Workbook
      STYLES_FILE = YAML.load(File.read(YOUR_YML_FILE)).deep_symbolize_keys
      PREDEFINED_STYLES = {}
      def initialize(options={})
        super
        initialize_with_styles
      end
      private
      def initialize_with_styles
        STYLES_FILE.each do |k,v|
          PREDEFINED_STYLES[k] = @styles.add_style(v)
        end
      end
    end
    

    Then you can initiate your Workbook from your custom class and reference styles through the PREDEFINED_STYLES constant.

    0 讨论(0)
提交回复
热议问题