可以将字体颜色应用于单个单元格,而无需创建样式:
Axlsx::Package.new do |p|
p.workbook.add_worksheet(:name => "test") do |ws|
ws.add_row ["a", "b", "c"]
ws.add_row ["d", "e", "f"]
ws.add_row ["g", "h", "i"]
ws.rows.each do |r|
r.cells.each do |c|
c.color = "009900"
if ['a', 'e', 'i'].include?(c.value)
c.color = "009900" // how can I do the same for background color?
end
end
end
end
p.serialize('test.xlsx')
end
可以将样式应用于单个单元格:
Axlsx::Package.new do |p|
p.workbook.add_worksheet(:name => "test") do |ws|
style1 = ws.styles.add_style( :bg_color => "FFFFFF00")
ws.add_row ["a", "b", "c"]
ws.add_row ["d", "e", "f"]
ws.add_row ["g", "h", "i"]
ws.rows.each do |r|
r.cells.each do |c|
if ['a', 'e', 'i'].include?(c.value)
c.style = style1
end
end
end
end
p.serialize('test.xlsx')
end
但在我的情况下这是不切实际的,因为我希望单元格背景是单元格值的函数,并且希望避免构建数百或数千种样式。
有什么建议吗?
答案 0 :(得分:2)
我会在一个代码块本身回答你的问题,为特定单元格添加样式并为单元格添加背景颜色,你可以这样做:
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 ["a", "b", "c"], :style => style1
ws.add_row ["d", "e", "f"], :bg_color
end
p.serialize('test.xlsx')
end
请注意: bg_color是背景颜色 fg_color是前景色(文本颜色)。
答案 1 :(得分:2)
您可以在更改模式下为行和单元格添加样式,您可以使用所需的行准备好工作表。这种方式可能过于静态,您必须对所有行和单元格详细信息进行硬编码。
package = Axlsx::Package.new
package.workbook.add_worksheet(name: 'Worksheet') do |sheet|
# after adding required rows
style1 = sheet.styles.add_style(:bg_color => "EF0920", :fg_color => "FFFFFF")
sheet.rows[6].cells[1].style = style1
end