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

excel表的当前状态如下:

这是使用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 那么,如何将日期列自动添加到表中呢?谢谢你们。
发布于 2018-04-17 19:14:36
我想你会想要这样做的:
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列的数目。但它应该会让你走上正确的道路!
https://stackoverflow.com/questions/45494822
复制相似问题