AXLSX merge cells inside a style

前端 未结 1 1807
孤街浪徒
孤街浪徒 2021-01-14 07:50

I\'m using ruby gem axlsx and want to know if there\'s a way to set merge columns inside a style? Today i doing like this:

sheet.merge_cells \"A1:E1\"
sheet         


        
相关标签:
1条回答
  • 2021-01-14 08:19

    Yes give this a try (*Disclaimer I did not actually test these methods but I have used similar functionality in the past)

    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
    

    so to do what you want it would be

    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
    

    If the last row contains data in A-E then the columns can be left empty and it will merge the whole row. If it does not you could add an option for filling the columns like so

    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
    

    calls as

    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
    

    If you are going to use these consistently then patching these functions into Worksheet might make more sense so you don't have to pass the sheet object.

    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
    

    Call

    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
    
    0 讨论(0)
提交回复
热议问题