我正在使用ruby gem axlsx,我想知道是否有一种方法可以在样式中设置合并列?今天我是这样做的:
sheet.merge_cells "A1:E1"
sheet.add_row [I18n.t('foo.some_label').upcase], style: [title]
sheet.merge_cells "B2:E2"
...
我想避免手动增加单元格(B2:E2...B5:E5),有办法做到这一点吗?
发布于 2014-05-14 23:17:57
是的,试一试(*免责声明我并没有实际测试这些方法,但我在过去使用过类似的功能)
def merge_last_row(sheet,options ={})
last_row = sheet.rows.last.index + 1
first_col,last_col = options[:columns]
if first_col && last_col
sheet.merge_cells "#{first_col}#{last_row}:#{last_col}#{last_row}"
else
sheet.merge_cells sheet.rows.last
end
sheet.rows.last.style = style if options[:style]
end
所以要做你想做的事情
merge_last_row sheet, columns:["A","E"]
sheet.add_row [I18n.t('foo.some_label').upcase]
merge_last_row sheet, columns:["B","E"], style:title
如果最后一行包含A-E中的数据,则可以将列保留为空,并合并整个行。如果没有,您可以添加一个用于填充列的选项,如下所示
def fill_columns(sheet,column_count,options={})
row = options[:row_data] || []
(column_count - row.count).times do
row << nil
end
sheet.add_row row
end
呼叫方式
my_row = ["Hello","World"]
fill_columns sheet, 5,row_data: my_row
# this will add a row like["Hello","World",nil,nil,nil]
# so that it will merge properly across the columns A-E
merge_last_row sheet
如果您打算始终如一地使用这些函数,那么将这些函数打补丁到Worksheet
中可能更有意义,这样就不必传递sheet
对象。
module Axlsx
class Worksheet
def merge_last_row(options={})
last_row = rows.last.index + 1
first_col,last_col = options[:columns]
if first_col && last_col
merge_cells "#{first_col}#{last_row}:#{last_col}#{last_row}"
else
merge_cells rows.last
end
rows.last.style = style if options[:style]
end
def fill_columns(column_count,options={})
row_data = options[:row_data] || []
(column_count - row.count).times do
row_data << nil
end
add_row row_data
end
end
end
打电话
sheet.merge_last_row columns:["A","E"]
sheet.add_row [I18n.t('foo.some_label').upcase]
sheet.merge_last_row columns:["B","E"], style:title
https://stackoverflow.com/questions/23657513
复制相似问题