不论是产各式报表,都与 Excel 脱离不了关系,产 Excel 属於必备技能之一,以下示范如何产 Excel 档
这边以 axlsx Gem 做范例,也有其他 Gem 也能做到,像是 xlsxtream 等,可参考此 pr
直接用 axlsx 最新版本直接 bundle 的话,会踩到雷,详情,自己装看看就知道了 XD
# Gemfile
gem 'rubyzip', '~> 2.3', '>= 2.3.2'
gem 'axlsx_rails', '~> 0.6.1'
gem 'axlsx', git: "https://github.com/randym/axlsx.git",
ref: "c8ac844572b25fda358cc01d2104720c4c42f450"
将产 Excel 写在 services,方便之後共用
# app/services/shops_excel/generator.rb
module ShopsExcel
class Generator
TITLES = %w[商家名称 信箱 备注].freeze
ROW_TYPES = %i[string string string].freeze
def execute
shops = Shop.all
xlsx = Axlsx::Package.new
workbook = xlsx.workbook
workbook.add_worksheet(name: '商家清单') do |sheet|
sheet.add_row(TITLES)
shops.find_each do |shop|
sheet.add_row(shop_row_data(shop), types: ROW_TYPES)
end
end
xlsx
end
private
def shop_row_data(shop)
[
shop.name,
shop.email,
shop.note
]
end
end
end
# config/routes.rb
get :export_shops_xlsx
---
# app/controllers/shops_controller.rb
def export_shops_xlsx
# 实务上,并不建议直接在 controller 直接产 Excel,若资料很多的话,使用者体验会不好 (会等很久)
xlsx = ShopsExcel::Generator.new.execute
send_data(xlsx.to_stream.read, type: 'application/xlsx', filename: '商家总表.xlsx')
end
若只是单纯产一次就不会再产的话,可以在 rails console
直接下 code,如下
# rails console
xlsx = ShopsExcel::Generator.new.execute
xlsx.use_shared_strings = true
xlsx_file = Rails.root.join("data/test.xlsx")
xlsx.serialize(xlsx_file)
产 Excel 其实不难,难的是产的资料内容过於复杂且多时,可能会关联超多 Model 、多个工作表 (worksheet),还要考量是否会 Memory Bloat
实务上并不建议直接在 controller 直接产 Excel ,资料太多的话,使用者体验会不好,会等很久,通常会放 sidekiq 处理,完成後,再寄信给使用者
铁人赛文章连结:https://ithelp.ithome.com.tw/articles/10272151
medium 文章连结:https://link.medium.com/GmNaDhwgQjb
本文同步发布於 小菜的 Blog https://riverye.com/
备注:之後文章修改更新,以个人部落格为主
<<: Ruby on Rails ⾃订验证器 Validator
Conclusion 呼~到今天为止 9 天过去了,Libraries 之间的比较篇章也到今天告一...
日志是会计的工作成果。可以通过查看或检查(审核)一组相关日志(审核记录)以唯一地将活动跟踪到实体来实...
-数位签章 使用您的私钥加密代码的指纹或对代码进行散列并使用您的私钥加密结果是生成数字签名的 改写...
昨天重新熟悉整个"游戏执行区"之後,就剩下两个主要的区块了 今天来看"...
如果有错误,欢迎留言指教~ Q_Q 没写完啦 子元件通常会接收父元件的 state 或 event...