首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Axlxs gem -自动添加日期列

问Axlxs gem -自动添加日期列
EN

Stack Overflow用户
提问于 2017-08-04 05:31:14
回答 1查看 941关注 0票数 0

我正在使用axlsx gem创建excel电子表格。在我的例子中,电子表格是为notes模型创建的。电子表格使用三个模型属性作为列:设计编号、体积和日期。每个日期列表示设备的体积。我想让日期列自动添加时,从备注表格的新数据。就像这样:

​

​

excel表的当前状态如下:

​

​

这是使用axlsx编写的代码:

代码语言:javascript
复制
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 

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

EN

回答 1

Stack Overflow用户

发布于 2018-04-17 19:14:36

我想你会想要这样做的:

代码语言:javascript
复制
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_at和date字段可以匹配非常重要。并且可能需要调整基于标题列的数目来指定要包括的@formats列的数目。但它应该会让你走上正确的道路!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45494822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档