rails 使用axlsx 导出excel

官方文档:https://github.com/randym/axlsx

安装

gem 'axlsx', '~> 2.0'

代码

exl = Axlsx::Package.new
exl.workbook.add_worksheet(:name => "Basic Worksheet") do |sheet|
sheet.add_row ["商家名称", "公司名称", "状态"]
    @shops.each do |shop|
          status = ApplicationController.helpers.get_shop_status(shop.status)
          sheet.add_row [shop.name, shop.company.name, status]
    end
 end
exl.use_shared_strings = true
send_data exl.to_stream.read, type: "application/xlsx", filename: "shops.xlsx"

这里使用了这位老哥的代码,因为我的代码的业务解释起来不方便

解释

代码整体很好理解

exl.workbook.add_worksheet(:name => "Basic Worksheet") do |sheet|

这部分是设置表格名字的,就是这个东西。
在这里插入图片描述

 @shops.each do |shop|
          status = ApplicationController.helpers.get_shop_status(shop.status)
          sheet.add_row [shop.name, shop.company.name, status]
    end

这部分是循环导入excel的内容,对应好上面的表头就好啦

send_data exl.to_stream.read, type: "application/xlsx", filename: "shops.xlsx"

设置一下导出excel文件的名字

ps:代码需要在controllers里面编写 ,生成后的文件会直接下载下来。
其实没啥需要解释的,我记性不好 ,写的啰嗦点。。

猜你喜欢

转载自blog.csdn.net/weixin_42656358/article/details/101483347
今日推荐