Axlxs gem - 自动添加日期列

时间:2017-08-03 21:31:14

标签: ruby-on-rails ruby excel xlsx axlsx

我正在使用axlsx gem来创建Excel电子表格。就我而言,为笔记模型创建了电子表格。电子表格使用三个模型属性作为列:设计编号,数量和日期。每个日期列表示设备的体积。我想在从notes表中获取新数据时自动添加日期列。像那样:

enter image description here

excel表的当前状态如下所示:

enter image description here

这是使用axlsx编写的代码:

wb = xlsx_package.workbook
wb.styles do |style|
    date_cell = style.add_style(format_code: "yyyy-mm-dd hh:mm")
    wb.add_worksheet(name: "Notes") do |sheet|
        sheet.add_row ["Devise number", "Volume", "Date"]
        @notes.each do |note|
            sheet.add_row [note.devise.number, note.volume, note.created_at],  
            style: [nil,nil, date_cell]
        end
    end
end 

那么,如何自动将日期列添加到表中?谢谢你们,伙计们。

1 个答案:

答案 0 :(得分:0)

我想你会想做这样的事情:

wb = xlsx_package.workbook
wb.styles do |style|
  date_cell = style.add_style(format_code: "yyyy-mm-dd hh:mm")
  # Set your dynamic headers
  @header_cols = []
  @header_cols << "Devise number"
  @notes.each do |n|
    @header_cols << n.date # Adds all dates from all notes to header columns
  end
  # Set dynamic format array based on headers
  @formats = []
  @formats << nil
  @header_cols.count.times do |f|
    @formats << date_cell
  end
  wb.add_worksheet(name: "Notes") do |sheet|
    sheet.add_row @header_cols # Use your dynamic column list
      @notes.each do |note|
        cols = []
        cols << note.devise.number # Always include this in the first place
        @header_cols.each do |c|
          if c == note.date
            cols << note.created_at
          else
            cols << "N/a" # Whatever blank value you want to appear
          end
        end
        sheet.add_row cols,
        style: @formats
      end
  end
end

未经测试。确保created_atdate字段可以匹配非常重要。并且可能需要根据标题列的数量指定要包括的@formats列的数量。但它应该让你走上正确的道路!