首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >AXLSX合并样式内的单元格

AXLSX合并样式内的单元格
EN

Stack Overflow用户
提问于 2014-05-14 22:27:19
回答 1查看 3.8K关注 0票数 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),有办法做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23657513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档