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:
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
The result is:
How can I color a date cell without losing the data information?
You will need to specify the number format as well so your style would look like
When adding a style it will overwrite the default style and all formatting. e.g.
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
Then style your rows as
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 constantsNUM_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.
Then something like
Then you can initiate your Workbook from your custom class and reference styles through the
PREDEFINED_STYLES
constant.