5

我正在使用 Ruby Spreadsheet gem 将数据从 rails 应用程序导出到 excel,有没有办法让列的大小自动调整为内容的大小?

4

2 回答 2

9

从来没听说过。我必须手动跟踪每列中字符串的长度,然后获取最大长度并为其添加更多单位,然后将列的宽度设置为该计算值。

account_name_lengths = []
# generate each row
accounts.each do |account|
  account_name_lengths << account.name.length

  # add to sheet here
end

sheet.column(0).width = account_name_lengths.max + 5
于 2013-08-13T15:58:23.567 回答
2

适合所有列

def auto_fit(sheet)
  (0...sheet.column_count).each do |col_idx|
    column = sheet.column(col_idx)
    column.width = column.each_with_index.map do |cell, row|
      chars = cell.present? ? cell.to_s.strip.split('').count + 4 : 1
      ratio = sheet.row(row).format(col_idx).font.size / 10
      (chars * ratio).round
    end.max
  end
end
于 2019-04-23T10:25:29.993 回答