rails uses axlsx to export excel

Official document: https://github.com/randym/axlsx

installation

gem 'axlsx', '~> 2.0'

Code

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"

The code of this old man is used here , because the business explanation of my code is not convenient

Explanation

The overall code is well understood

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

This part is to set the name of the table, and that is it.
Insert picture description here

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

This part is to import the content of excel circularly, just correspond to the header above

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

Set the name of the exported excel file

ps: The code needs to be written in controllers, and the generated file will be downloaded directly.
In fact, there is nothing to explain, I have a bad memory, and I write a little bit verbose. .

Guess you like

Origin blog.csdn.net/weixin_42656358/article/details/101483347