3

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)、これを行う方法はありますか?

4

1 に答える 1

7

はい、試してみてください (*免責事項: これらのメソッドを実際にテストしたわけではありませんが、過去に同様の機能を使用したことがあります)

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

最後の行に AE のデータが含まれている場合、列を空のままにしておくと、行全体がマージされます。そうでない場合は、そのように列を埋めるためのオプションを追加できます

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
于 2014-05-14T15:17:56.520 に答える