如何用axlsx给出日期背景颜色?

时间:2016-10-21 14:21:11

标签: ruby excel 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

结果是:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

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

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

还有numFmtsglobal 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

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