axlsx:acts_as_xlsx:我如何只为一个单元格添加样式?

elu*_*bin 7 format axlsx

我看到col_style和row_style以及add_conditional_formatting的方法,但无法弄清楚如何只设置一个单元格.在我的示例中,col 1是日期,列2是百分比.当我突出显示行的背景时,我会丢失日期/百分比格式,因为Randy解释说一个单元格只能有1种样式.如何在必要时将date_with_background样式分配给该行中的第一个单元格?

xlsx_package = Stuff.all.to_xlsx
xlsx_package.workbook.worksheets.first.tap do |sheet|

  sheet.col_style 0, date_format, {row_offset: 1}
  sheet.col_style 1, percent_format, {row_offset: 1}

  list_of_my_stuff.each_with_index do |item,index|
    if needs_background?(item)
      sheet.row_style index+1, with_background
    else
      sheet.row_style index+1, no_background
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

gen*_*abs 5

我也想设计一个单元格的样式,而不是在创建表时进行同步,而是实际上对其进行编辑。如果合并一堆单元格,这将非常有用。在axlsx文档中并没有真正强调它,但是您可以直接访问单元格及其样式。

像这样:

wb = xlsx_package.workbook

wb.styles do |s|

  title_style = s.add_style :sz => 20, :alignment => { :horizontal=> :center }, :border => { :style => :thick, :color => "000000", :edges => [:left, :right, :top, :bottom] }

  wb.add_worksheet(name: "Standard Chart") do |sheet|

    #make a 30x30 spread sheet testbench of one space cells
    30.times { sheet.add_row Array.new(30, " ") }

    #merge some particular cells into a 4x4 block
    sheet.rows[7].cells[5].merge sheet.rows[10].cells[8]

    #set values for our merged cell and one on either side
    sheet.rows[7].cells[4].value = 'foo'
    sheet.rows[7].cells[5].value = "I am cell #{sheet.rows[7].cells[5].r}"
    sheet.rows[7].cells[9].value = 'bar'

    #style ONLY our merged cell
    sheet.rows[7].cells[5].style = title_style
  end

end #end styles

xlsx_package.use_shared_strings = true
Run Code Online (Sandbox Code Playgroud)

希望能帮助某人^ _ ^


Tra*_*tto 1

要将样式仅应用于一个单元格,当您调用 add_row 时,您可以在末尾指定一组样式。将您的样式放在第一个中,其余部分用 nil 填充。我认为如果您在数组中只有一种样式,就像您希望在第一列中那样,它也可能有效,但我不确定。有空就去尝试一下。

例子:

my_style = sheet.add_style :b=>true

sheet.add_row ["One","Two","Three"],:styles=>[my_style].fill(1..2,nil)
Run Code Online (Sandbox Code Playgroud)

  • 将 :styles 选项传递给 add_row 时,行为会根据 :styles 值的数据类型而变化。如果它是一个数组,样式将按数组的索引顺序应用于每个单元格。超出数组长度的单元格将不会被设置样式。您可以在该数组中的任何位置使用 nil 来不为单元格数据数组中的任何元素指定样式。如果 :styles 是一个整数,它将应用于该行中的所有单元格。无论哪种方式,发布者都只能访问 row_style 和 col_style,因为它们使用acts_as_xlsx。 (2认同)