Rails AXLSX sort.cells

时间:2014-08-04 18:38:07

标签: ruby-on-rails axlsx

我在Rails应用中使用gem 'axlsx_rails'

我想对单元格(A列第2行到第23行)进行排序,作为创建标签的最后一步。

这是我的代码:

wb.add_worksheet(:name => "Cost") do |sheet|
  sheet.page_setup.set :orientation => :portrait
  sheet.add_row ['Seq', 'Category', 'Remarks', 'Amount', 'Notes'], :style => [header_cell, header_cell, header_cell, header_cell, header_cell]
    @costproject.costestimates.each do |costestimate|
      sheet.add_row [costestimate.costcat.position, costestimate.costcat.category_name, costestimate.costcat.categorydesc, number_with_precision(costestimate.amount, :precision => 2), costestimate.notes], :style=> [intgr,nil,nil,money]
    end
  sheet.add_row [nil, 'TOTAL', nil, "=SUM(D2:D23)"]
  sheet.column_widths 5, 35, 25, 25
  cells.sort ?????
end

我认为这可以做到。是对的吗? 如果有,怎么样?我应该用{<1}}替换什么?

感谢您的帮助!

更新1:

感谢emcanes,我在add_row期间对记录进行了排序:

cells.sort ?????

我仍然想知道AXSLX是否可以使用 sheet.add_row ['Seq', 'Category', 'Remarks', 'Amount', 'Notes'], :style => [header_cell, header_cell, header_cell, header_cell, header_cell] @costproject.costestimates.includes(:costcat).order("costcats.position").each do |ce| sheet.add_row [ce.costcat.position, ce.costcat.category_name, ce.costcat.categorydesc, number_with_precision(ce.amount, :precision => 2), ce.notes], :style=> [intgr,border,border,money,border] end ??

1 个答案:

答案 0 :(得分:0)

通过工作表可以使用rows SimpleTypedList,虽然没有sheet.rows=方法,但您可以使用sort_by!对其进行修改:

wb.add_worksheet(:name => "Cost") do |sheet|
  # your other code
  first_row = sheet.rows.first
  last_row  = sheet.rows.last
  # get a total position higher than all others
  tpos = sheet.rows.map {|row| row.cells[0].value.to_i}.max + 1
  sheet.rows.sort_by! do |row|
    (row == first_row ? -1 : (row == last_row ? tpos : row.cells[0].value.to_i))
  end
  # now do styling
end

行没有内部索引,因此您无法询问它是什么索引。如果你问的话,它只是找出它在行列表中的位置。所以你必须提前保存标题/总行数。

我没有测试过造型,但我不确定它会不会出现这种情况,因为这会让Axlsx的内部结构变得混乱。它可能需要在之后发生,除非它是通用的。

顺便说一下,使用Axlsx::cell_r函数来获取总范围:

"=SUM(D2:#{Axlsx::cell_r(3,@costproject.costestimates.length)}"

由于它期望基于零的索引,实际长度将计算标题行。 22估计会给你“D23”。