Ruby on Rails 使用 axlsx 简单方法

假如我要导出用户的信息:
首先,Gemfile 文件里添加:

gem 'axlsx', '= 2.0.1'
gem 'axlsx_rails'

运行

bundle install

然后在 UsersController 里添加一个方法

  def export_user_profile
    @users = User.all
    render "export_user_profile.xlsx.axlsx"
  end

然后需要在对应的 View 目录下新建一个 “export_user_profile.xlsx.axlsx” 文件,内容为:

wb = xlsx_package.workbook
wb.add_worksheet(name: "用户数据") do |sheet|
  sheet.add_row %w(
    姓名
    电话
    邮箱
    微信号
 )
  @users.find_each do |user|
    sheet.add_row [
        user.name,
        user.profile.phone,
        user.profile.email,
        user.profile.wechat_id,
    ]
  end
end

然后在你想要导出数据的页面添加一个链接:

= link_to "|  用户信息导出到 EXCEL", admin_export_user_profile_path(format: :xlsx), method: 'post'

ok,完事儿了。

posted @ 2020-04-16 15:00  Mr-Ran  阅读(241)  评论(0编辑  收藏  举报