You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中使用Spreadsheet gem在表格底部添加数据

解决Spreadsheet gem导出Excel时底部添加额外数据的问题

要在表格底部添加额外数据,核心是找到用户数据的最后一行位置,然后在该位置之后插入新行。以下是修改后的完整实现:

def download
  headers = ['User Name', 'Type']

  content_stream = StringIO.new

  workbook = Spreadsheet::Workbook.new
  users_sheet = workbook.create_worksheet name: 'Users'

  # 设置表头
  users_sheet.row(0).concat(headers)
  header_format = Spreadsheet::Format.new(weight: :bold)
  users_sheet.row(0).default_format = header_format

  # 写入用户数据
  @users = User.all
  @users.each.with_index(1) do |user, index|
    users_sheet.row(index).push user.full_name, user.type
  end

  # 在表格底部添加额外数据(示例:统计用户总数)
  # 获取最后一行的下一个索引
  bottom_row_index = users_sheet.last_row + 1
  # 设置底部数据的格式(可选,比如加粗)
  bottom_format = Spreadsheet::Format.new(weight: :bold)
  # 写入数据,合并两列显示统计信息
  users_sheet.row(bottom_row_index).push "Total Users: #{@users.count}"
  users_sheet.merge_cells(bottom_row_index, 0, bottom_row_index, 1)
  users_sheet.row(bottom_row_index).default_format = bottom_format

  # 自动调整列宽(必须在所有数据写入完成后调用)
  auto_fit(users_sheet)

  workbook.write(content_stream)
  content_stream.rewind

  send_data(content_stream.read, filename: "users.xls")
end

private

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|
      next 1 unless cell.present?
      chars = cell.to_s.strip.split('').count + 4
      ratio = sheet.row(row).format(col_idx).font.size / 10.0
      (chars * ratio).round
    end.max || 10 # 防止无数据时列宽计算出错
  end
end

关键修改点说明:

  • 定位底部行:用users_sheet.last_row获取已有数据的最后一行索引,加1即为新数据的起始行位置。
  • 添加底部数据:按需写入内容,示例中合并两列展示用户总数,并设置加粗格式匹配表头风格。
  • 调整列宽时机:把auto_fit调用移到所有数据(包括底部额外数据)写入完成后,确保新内容也能适配列宽。
  • 优化列宽计算:增加兜底逻辑,避免无数据场景下出现计算错误。

当前表格效果:
当前表格效果

期望表格效果:
期望表格效果

内容的提问来源于stack exchange,提问作者user12763413

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:23:35