【问题标题】:rails http response to Donwload excel filerails http响应下载excel文件
【发布时间】:2020-10-26 01:47:52
【问题描述】:

我在 github 上看到了这段代码

require "csv"

csv_str = CSV.generate do |csv|
 csv << ["awesome", "csv"]
end

result = IO.popen("secure-spreadsheet --password secret", "r+") do |io|
 io.write(csv_str)
 io.close_write
 io.read
end

File.open("output.xlsx", "w") { |f| f.write(result) }

此代码在我的项目文件中存储了一个 Excel 文件(output.xlsx)。

如何将此“存储文件方案”转换为“在浏览器中下载文件”?

【问题讨论】:

    标签: ruby-on-rails ruby http ruby-on-rails-5


    【解决方案1】:

    在您的 config/initializers/mime_types.rb 中注册 xlsx mime_type(Rails 默认不提供):

    Mime::Type.register "application/xlsx", :xlsx
    

    假设您生成 excel 的代码有效并且位于名为 excel_file 的控制器方法(私有)中(我认为最好提取到服务/lib 类):

    def excel_file
      csv_str = CSV.generate do |csv|
        csv << ["awesome", "csv"]
      end
    
      IO.popen("secure-spreadsheet --password secret", "r+") do |io|
        io.write(csv_str)
        io.close_write
        io.read
      end
    end
    
    

    在您的控制器操作中,您应该能够执行类似的操作

    def download_excel
      respond_to do |format|
        format.xlsx { send_data excel_file, type: 'application/xlsx; header=present', disposition: "attachment", filename: "output.xlsx"  }
      end
    end
    

    ActionController#send_data“将给定的二进制数据发送到浏览器”。通过该链接了解更多信息)

    有观点可以有下载链接

    <%= link_to "Download", your_download_path(format: "xlsx") %>
    

    用户应该可以通过链接下载excel文件

    【讨论】:

    • 让我试试这个我的朋友
    • 我会在 caxlsx gem 中试试这个我希望这会奏效
    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    相关资源
    最近更新 更多