如何使用 axlsx 为日期设置背景颜色?

How to give a date a background color with axlsx?

我用 axslx 创建了一个 excel。 一排应该是彩色的。但是,如果我这样做,我就失去了我日期的日期格式。

我做了一些尝试的最小示例:

require 'axlsx'
Axlsx::Package.new do |p|
    p.workbook.add_worksheet(:name => "test") do |ws|
        style1 = ws.styles.add_style(:bg_color => "EF0920", :fg_color => "FFFFFF")
        ws.add_row [ Date.today, "No style defined --ok"]
        ws.add_row [ Date.today, "Style with colors --The date is no date any longer"], :style => style1
        ws.add_row [ Date.today, "Style with colors, except date -- ok, but not colored"], :style => [nil,style1]
        ws.add_row [ Date.today, "Style with colors and types --The date is no date any longer"], :style => style1, :types => [:date,:string]
        ws.add_row [ Date.today, "Style with colors and types --The date is no date any longer"], :style => [style1,style1], :types => [:date,:string]
        ws.add_row [ Date.today, "No Style -- ok, but not colored"], :types => [:date,:string]
    end
    p.serialize('test.xlsx')
end

结果是:

如何在不丢失数据信息的情况下为日期单元格着色?

您还需要指定数字格式,以便您的样式看起来像

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

添加样式时会覆盖默认样式和所有格式。例如

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

这将生成一个与其他行一样格式的红色日期和一个无填充列 B。

此样式仅适用于日期,因此如果您想要整个专栏,我会推荐类似

的样式
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)

然后将您的行设置为

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

这将生成红色行(A 列和 B 列),日期格式与其他行相同。

Git Hub Source

还可以通过 numFmts and the global named constants NUM_FMT_PERCENTAGENUM_FMT_YYYYMMDDNUM_FMT_YYYYMMDDHHMMSS 等方式使用预定义样式

当定义许多不同的格式时,我发现使用 YML 文件然后解析它来定义样式是最简单的,例如

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

然后是

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

然后您可以从您的自定义 class 启动工作簿并通过 PREDEFINED_STYLES 常量引用样式。