【问题标题】:AXLSX merge cells inside a styleAXLSX 合并样式内的单元格
【发布时间】:2014-05-14 14:27:18
【问题描述】:

我正在使用 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),有办法做到这一点吗?

【问题讨论】:

  • 我不清楚你在问什么。您是否正在寻找一种将其置于循环中的方法?

标签: ruby-on-rails ruby axlsx


【解决方案1】:

是的,试试这个(*免责声明我没有实际测试这些方法,但我过去使用过类似的功能)

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

【讨论】:

  • 包含这些方法的文件应该在我的 mixin 文件夹中吧?
  • @Rafael 你可以将它们放在你喜欢的任何地方,只要你将它们包含在你正在使用它们的文件中。对于 Rails,如果你使用补丁方法,你可以将它们放在初始化程序文件夹中然后这些方法将始终可以访问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
相关资源
最近更新 更多