5

可以将字体颜色应用于单个单元格,而无需创建样式:

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

但在我的情况下,这是不切实际的,因为我想让单元格背景成为单元格值的函数,并且希望避免构建数百或数千种样式。

有什么建议么?

4

2 回答 2

3

我会在一个代码块本身中回答您的问题,为特定单元格添加样式并为单元格添加背景颜色,您可以这样做:

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 是前景色(文本颜色)。

于 2014-10-15T22:23:04.117 回答
3

您可以在更改模式下为您的行和单元格添加样式,在这种模式下,您将准备好包含所需行的工作表。这种方式可能过于静态,您必须对所有行和单元格详细信息进行硬编码。

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
于 2017-03-02T05:09:04.577 回答